• Post Reply Bookmark Topic Watch Topic
  • New Topic

Doubt about boolean  RSS feed

 
shiva thadakamadla
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ,
The following code prints an output of false
class Bool {
static boolean b ;
public static void main(String [] args) {
boolean k = b=true;
System.out.println("k"+k);
}
}
and the following code prints an output of true
class Bool {
static boolean b ;
public static void main(String [] args) {
boolean k = b=true;
System.out.println("k"+k);
}
}
Can anybody explain how to understand this
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm afraid that I don't see any difference between the two code snippets. Either my eyes are going, or you may want to check to see if they are correct.
 
shiva thadakamadla
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am sorry. Problem of copy paste.
The quetion is like this:
The following code prints an output of true
class Bool {
static boolean b;
public static void main(String [] args) {
boolean k = b=true;
System.out.println("k"+k);
}
}
and the following code prints an output of false
class Bool {
static boolean b;
public static void main(String [] args) {
boolean k = b=false;
System.out.println("k"+k);
}
}

Please let me know the reason
 
Richard Teston
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Shiva,
In JLS 15.26 all assignment operator(especially "=") are syntactically right-associative which means java evaluate assignment expression from right to left. In your case static boolean b; had been implicitly assigned to a default value which is false but when java execute the line boolean k = b = true; java group it as boolean k = (b = true) now b was been evaluated as true so boolean k = true; the same thing goes to expression boolean k = b=false;. So remember all assignment expression (expression with =, *=, /=, %=, +=, -=, <<=, >>=, >>>=, &=, ^= and |= operator)is right associative.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!