• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

bool?

 
sonir shah
Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider this:
boolean bool = true; int k = 10;
if( bool == false && ( (k = 3) == 5 ) ) { .....}
System.out.println(k); // this will print 10.
Ans : 10
But bool declared is true and then in the condition it checks that whether bool is false, the answer is false
Then why is the value of k printed?
Sonir
 
Axel Janssen
Ranch Hand
Posts: 2166
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if( bool == false && ( (k = 3) == 5 ) ) { .....}
System.out.println(k); // this will print 10.

because the if () {} block ends were marked bold.
It will not print out 3 because && uses short circuit optimization. Both conditions have to be true to execute the {}. If first condition it false the second condition will be allways skipped if you use &&.
Hope it helps.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic