1

I really don't understand this kind of "operations" or what are they called :

System.out.println((1<2) ?5: (3<4)   +   "   ");

Is the same with this code ?

if(1<2)
   return 5;
else if (3<4)

But after ':' it says Dead code . Why is that ?

2

2 Answers 2

2

Compiler evaluates constant expressions at compile time. Because of that, the expression 1<2 is fully equivalent to the expression true, making the initial part of your conditional expression look like this:

System.out.println((true) ? 5 : (3<4)   +   "   ");
//                 ^^^^^^^^^^   ^^^^^
//        Important code          |
//                                |
//        Useless code -----------+

The compiler does not stop at evaluating 1<2, it goes on to evaluating the rest of the expression, which produces 5.

Sign up to request clarification or add additional context in comments.

Comments

0

Your code is weird, I really do not understand what are you trying to achieve. I think it is wrong, it should be like this:

return 1 < 2 ? 5 : 3 < 4 ? 1 : 2;

You can rewrite it into if-else form:

if (1 < 2)
    return 5;
if (3 < 4)
    return 1;
return 2;

Since return causes the program to jump out of function, else is not needed in this particular example.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.