In C++, this expression will compile, and when ran, will print test:
    if(!1 >= 0) cout<<"test";
but in Java, this will not compile:
    if(!1 >= 0) System.out.println("test");
and instead parentheses are needed:
    if(!(1>=0)) System.out.println("test");
but test will not print since 1 >= 0 is true, and NOT true is false.
So why does it compile AND print out test in C++, even though the statement is false, but not in Java?
Thanks for your help.
This occurs because !1 is valid in C++ but not in Java1.
Both languages parse !1>=0 as (!1)>=0 because (in both C+ and Java) ! has as higher precedence than >=.
So (in C++), (!1)>=0-> 0>=0 -> true but (in Java) !1 (!int) is a type error.
However (in either C++ or Java), !(1>=0) -> !(true) -> false.
1 Java only defines the ! operator over the boolean type.
In java unary operator ! has high precedence than conditional operator >=. That why it needs parenthesis  ().
Here is the details table of operator precedence of Java.
But, In C++ positive value in condition refer as boolean true value. So, if(!1>=0) is valid in C++ but invalid in Java. In Java, boolean value is only true and false. It never treat positive value as true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With