Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

operator precedence

 
dolly shah
Ranch Hand
Posts: 383
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int i = 10;
int j = 10;
boolean b = false;
if( b = i == j)
System.out.println("True");
else
System.out.println("False");


Compilation error at line 4.
Runtime error exception at line 4.
Prints "True".-answer
Prints "False".

explanation
Conditional operators have higher precedence than assignment operator.

Here in if statement if( b = i == j), It should be if( b =( i == j)). If I am wrong please correct me.
 
Akhilesh Trivedi
Ranch Hand
Posts: 1607
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by dolly shah:
int i = 10;
int j = 10;
boolean b = false;
if( b = i == j)
System.out.println("True");
else
System.out.println("False");


Compilation error at line 4.
Runtime error exception at line 4.
Prints "True".-answer
Prints "False".

explanation
Conditional operators have higher precedence than assignment operator.

Here in if statement if( b = i == j), It should be if( b =( i == j)). If I am wrong please correct me.



Even if it goes that way what exactly you get inside the "if"? Remember "if" can have only results of type boolean inside the parentheses.
 
dolly shah
Ranch Hand
Posts: 383
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If if statement is like (b=(i==j)), then it sets b=true that is still o.k.
My question is why (b=i==j) is legal?
 
dolly shah
Ranch Hand
Posts: 383
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got it. It works on precedence. So (==) evaluates, that gives true. After that (=) to b, So result is "true".
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic