0

Is there any noticeable difference between

boolean foo= bar>1;

and

boolean foo = bar>1? true:false;

I have noticed that in the first example, the condition is evaluated immediately, looking something like this.

int bar=3;
boolean foo= bar>1;
bar =0;
if(foo){
    System.out.println("Foobar");
}

Would print Foobar, whereas if the condition were to be inside the if statement, it would not print at all. This so far is identical to giving the boolean variable a true/false value from the start with the ternary operator or if/else

2 Answers 2

3

The ternary is highly redundant. Given that the inequality will return a boolean result, you do not need to perform any kind of ternary operation on it whatsoever.

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

1 Comment

That's what I thought, because I knew it wasn't evaluating the variable inside the if statement, I was just making sure there wasn't any extra nuance to it.
1

One thing I like to add along with, both of the code will generate the same bytecode. For the proof you can use the Java Class File Disassembler (javap)

use the command to disassemble the class files javap -c com.package.MyClass and you will find for the both of the code JVM will generate the same bytecode. Hence there is No benefit or harm for either of the two statement. But definitely ternary here is redaundant

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.