my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes operator precedence Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "operator precedence" Watch "operator precedence" New topic
Author

operator precedence

dolly shah
Ranch Hand

Joined: Jun 18, 2007
Posts: 383
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.


SCJP-1.5<br />SCWCD-1.4
Akhilesh Trivedi
Ranch Hand

Joined: Jun 22, 2005
Posts: 1527
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.


Keep Smiling Always — My life is smoother when running silent. -paul
[FAQs] [Certification Guides] [The Linux Documentation Project]
dolly shah
Ranch Hand

Joined: Jun 18, 2007
Posts: 383
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

Joined: Jun 18, 2007
Posts: 383
I got it. It works on precedence. So (==) evaluates, that gives true. After that (=) to b, So result is "true".
 
GeeCON Prague 2014
 
subject: operator precedence