Bitwise operators (&, XOR, <<, ...) - 1

"Hi, Amigo!"

"One more little lesson about bitwise operators."

"You know that in addition to the logical operators AND (&&), OR (||) and NOT (!), there are also bitwise operators AND (&), OR (|), NOT (~), and XOR(^), right?"

"Yep. Bilaabo once gave a very good lesson about this."

"Well, about these operators. I've got two things to tell you:"

"First, except for NOT (~), they can be applied to boolean variables, just like logical operators."

"Second, lazy evaluation does not apply to them."

"Look at this example:"

Code Equivalent code
if (a != null && a.getName() != null && c != null)
{
 c.setName(a.getName());
}
if (a != null)
{
 if (a.getName() != null)
 {
  if (c != null)
  {
   c.setName(a.getName());
  }
 }
}

"Is the left side more compact than the right?"

"Yep."

"And does it have the same meaning?"

"Yep."

"Quite right. But now look at the same expression using bitwise operators:"

Code Equivalent code
if (a != null & a.getName() != null & c != null)
{
 c.setName(a.getName());
}
boolean c1 = (a != null);
boolean c2 = (a.getName() != null);
boolean c3 = (c != null);
if (c1)
{
 if (c2)
 {
  if (c3)
  {
   c.setName(a.getName());
 }
 }
}

"In other words, the code is the same, but absolutely every operation will be performed."

"Note that if a is null, an exception will be thrown when calculating c2!"

"Ah. I can see that more clearly now."