• Post Reply Bookmark Topic Watch Topic
  • New Topic

precedence of operators  RSS feed

 
sirisha sirisha
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Q10 {
public static void main ( String [ ] args ) {
int i = 10 ;
int j = 10 ;
boolean b = false ;

if( b = i == j ) // ---> line 1
System . out . println ( " True " ) ;
else
System . out . println ( " False " ) ;
}
}

in the above code , it prints true.in the if expression it is evaluated from right to left .initially when i say b=i , i thouhgt compiler error , but it printed true.

whenever boolean and primitives are mixed , it is a bit confsing for me.
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
== has higher precedence than = so == is evaluated first which is true. that is assigned to b.
[ April 20, 2006: Message edited by: Keith Lynn ]
 
bnkiran kumar
Ranch Hand
Posts: 176
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sirisha,

you are right that = is evaluated from right to left if we have more than one , for example,
x=y=z;(x=(y=z))
but in this example there is only one =,so according to precedence, == is evaluated which results to true which in turn assign the result to boolean variable so true is printed.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!