Search code examples
javacoding-stylebehaviorscripting-language

Scripting-like behaviour in a non-scripting language


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.


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