• 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
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

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".
 
Never trust an airline that limits their passengers to one carry on iguana. Put this tiny ad in your shoe:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic