Question

I was playing around the ternary operator in Java when suddenly this question came to my mind. In PHP we can use the ternary operator for the decision and then put some command (or tags) in the main document like this (an example from the PHP manual.):

echo (true?'true':false?'t':'f');

Now, is something similar to this possible in Java? Like, is anything similar to the code below possible?

jButton1.getText().equals("hi")?jLabel1.setText("one"):jLabel1.setText("two")

What I want is, only one of the statements should be executed according to the true/false value. I know that this can better be done by using a if-else construct, but I just got curious and asked this question.

Was it helpful?

Solution

Use this instead:

jLabel1.setText(jButton1.getText().equals("hi") ? "one" : "two");

According to the JLS, this operator is called the conditional operator in Java. You can see by reading the preceding link that

it is a compile-time error for either the second or the third operand expression to be an invocation of a void method

OTHER TIPS

Or:

jButton1.getText ().equals ("hi") && jLabel1.setText ("one") || jLabel1.setText ("two");

JRLs solution is much more elegant, but if you like to manipulate different labels, depending on "hi", you might need such an approach.

Java definitely has a ternary operator. It looks to me like you're using it right. I would try to play around with the parenthesis if it was giving me problems, but it looks like you're using it right.

Java Term of the Week: Ternary Operator is explaining it, though.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top