• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Short Circuit operators and Bitwise operators

 
Vinal Kalyan
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am having trouble understanding what happens when short-circuit operators and bitwise operators are combined in an expression producing a boolean result. The following code has both a && operator and a | operator.

I thought that the following code would update the count variable to 1, because the ba.b[++ba.count] | true would be first evaluated because " | " holds higher order of precedence than " && ". However, I found out that it does not evaluate that all, and short-circuits, with the count variable not being updated.

public class BoolArray {
boolean [] b = new boolean[3];
int count = 0;

public static void main(String[] args) {
BoolArray ba = new BoolArray();
ba.b[0] = false;
ba.b[1] = false;
ba.b[2] = false;

if (false && ba.b[++ba.count] | true) {
System.out.println("We are here");

}
System.out.println(ba.count);

Thanks

Vinal.
 
Jeff Bosch
Ranch Hand
Posts: 805
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


By having "(false&&", the condition is automatically false and will go no further in evaluation because you've told the compiler to use the shortcut operator. Had you used "(false&" it would continue evaluating.

That's my story and I'm sticking to it...
 
Bert Bates
author
Sheriff
Posts: 8898
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Disclaimer: I didn;t read either the question OR the answer in any detail...

I would like to say however that if you're studying for the Tiger exam you don't need to worry about the bitwise operators.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic