File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Short Circuit operators and Bitwise operators Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Short Circuit operators and Bitwise operators" Watch "Short Circuit operators and Bitwise operators" New topic

Short Circuit operators and Bitwise operators

Vinal Kalyan

Joined: Feb 01, 2005
Posts: 3

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");



Jeff Bosch
Ranch Hand

Joined: Jul 30, 2003
Posts: 805

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...

Give a man a fish, he'll eat for one day. Teach a man to fish, he'll drink all your beer.
Cheers, Jeff (SCJP 1.4, SCJD in progress, if you can call that progress...)
Bert Bates

Joined: Oct 14, 2002
Posts: 8898
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.

Spot false dilemmas now, ask me how!
(If you're not on the edge, you're taking up too much room.)
I agree. Here's the link:
subject: Short Circuit operators and Bitwise operators
It's not a secret anymore!