Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Did `if ( x = 0 )` was ever Java compilable

I was intrigued that Scott Ambler in his book, Java Coding Standards, says, and I quote :

2.5.2 Place Constants on the Left Side of Comparisons

So he recommends to use

if ( 1 == something ) {…}    
if ( 0 = x ) { …}

instead of

if ( something == 1 ) {…}    
if ( x = 0 ) { …}  

OMG !!!

And he motivate this by saying that :

"Although they are both equivalent, at least on first inspection, the code on the left compiles and the code on the right does not."

As I'm aware (when I started programming Java, Java 14. was already in use), both of conditions will throw compiler error.

Starting from Ambler statement, I tried to search if Java syntax if ( x = 0 ); was ever compilable.

Can you help me out with this? I searched back different versions of JSR's and I did not find any change that could indicate that that piece of code was compiling on other java versions.

I compiled with a Jre7 compiler using target and source 1.2 and still raises compiler error. Unfortunately I don't have a Java 1.1 compiler: 9

My question is:

if(x = 0); Was compilable with older versions of Java compilers?

like image 212
Grandanat Avatar asked Dec 25 '22 19:12

Grandanat


2 Answers

it is not compilable. if (x=true) however still is if x is boolean.

like image 168
popfalushi Avatar answered Dec 28 '22 09:12

popfalushi


This condition if ( x = 0 ) { …} if ( 0 = x ) { …} will never compile.It is because if accepts boolean type but x=0 are assignment operators

secondly 0=x is not right.0=x means that you are storing the value of x in 0 which can never be possible.

In this condition if ( something == 1 ) {…} instead of if ( 1 == something ) {…} is valid one and will work well with the present comparison with integers but for comparison between strings instead of == better use .equals() Please see this links to know difference between == and .eqauls() link1 link2

like image 41
SpringLearner Avatar answered Dec 28 '22 11:12

SpringLearner