Help coderanch get a
new server
by contributing to the fundraiser
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

operator precedence

 
Ranch Hand
Posts: 383
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 1609
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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".
 
I am mighty! And this is a mighty small ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/t/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic