SCJP note #2: On logical operators

Believe me, this day has positively raised my hopes on monetizing the blog and publicly offering internet services. To put my thoughts back on reviewing, I’m writing a very important thing I learned from my “last reading”. I had my training 2 years ago but I never concentrated on logical operators, short circuit logical operators, in particular.

There are actually 4 logical operators in Java 2:

  • && - short circuit AND
  • || - short circuit OR
  • & - (bitwise) AND
  • | - (bitwise inclusive) OR

When used in expressions such as
if ((x<3) && (y>9))
the difference between the two set (short circuit and bitwise) of operators lie in their evaluation.

Using &&, given for example that x=5, only the first expression is computed. I was wondering how I got wrong in that one loopy problem involving this. Since it takes two true arguments for the AND operator to evaluate a true result, the second one in the example isn’t worth evaluating anymore.

If the first expression in a (short circuit) AND results to false, the other is left unevaluated. On the other hand, a (short circuit) OR operator halts the evaluation of the second expression if the first one evaluates to true. Remember that it only takes at least one true argument in order for the OR operator to return true.

In other words, short circuit logical operators save time. This doesn’t happen when using bitwise & and | operators, which surprisingly (for me) can also be used to evaluate logical arguments.

-

Just some rants on my exam schedule. I didn’t expect the Taiwan earthquake to have such a toll on me. I called the testing center and I *might* not be able take the exam before February ends because of the telecom cables that have yet to be repaired. Need to pray hard this time.

Leave a Reply