In C++ I'm able to do something like this

(some_condition)? function1():function2();

When i tried the same thing in Java it's not possible. It wants some variable to hold the result even though the return type of function1 and function2 are void.

Is there any other way to do it other than if... else...?

That didn't seem right to me, so I tried it. Here's the code:

public static void main(String[] args) {
		System.out.println(true?ifTrue():ifFalse());
	}

	
	public static String ifTrue()
	{
		return "It's twue, it's twue";
	}
	public static String ifFalse()
	{
		return "You liar!";
	}

And the output:

It's twue, it's twue


I suspect you're trying to use a ternary to fire an action. This is not what it's for.
The ternary is a device for selecting one of two expressions based on a condition inline rather than by evaluating, stuffing a variable, and then sticking the variable into an expression. It can fire methods, but in the end, the whole thing has to evaluate to an expression of some sort.
It's not an if statement.

From the JLS:

Note that it is a compile-time error for either the second or the third operand expression to be an invocation of a void method. In fact, it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear

ok thanks :)
so it seems like I have to invoke methods, then I should stick with if-else

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.