Logical vs. Bitwise

I started a new job not too long ago. All new hires at my company need to go through a couple months of training. That’s fine; I actually see it as a good thing. I’ve been learning how the company works, who is in charge of what and what I need to do when I screw up.

A large part of the training actually involves teaching newcomers how to code. This is actually the main focus of the training as they hire people who have majored in math or economics and don’t have a background in code. Having quite a large background in code, the training has been rather dull. But it’s still good for me to know how the company works, and it has made me comfortable enough that I won’t have the pressure of a new job bearing down on me once I actually start doing important work.

But my background also gives me a different perspective on coding and the specifics of languages that I’ve used. When they are told things about a language, they just have to accept it and move on without really questioning the reasons. For instance: they were taught that the difference between & and && in Java has to do with what exactly is executed when used in an if statement.

So, the following two if statements are executed differently. The first will not execute obj.hasElements() when obj is null, while the second statement will throw a NullPointerException.

if(obj != null && obj.hasElements()) {
    obj.run();
}

if(obj != null & obj.hasElements()) {
    obj.run();
}

Of course, this is correct; however, I have a problem with explaining the difference between the two AND statements for a couple reasons. Firstly, BitwiseAND and BitwiseOR are my namesake websites, and really are close to my heart. When described so poorly, I feel a need to speak out on their behalf. Secondly, the second if statement really wouldn’t be used this way; at least not in Java (I could see this occurring in C++ quite a bit). Bitwise operators (&, |, ^, …) are for manipulating bits, not booleans (as the name implies). Likewise, logical operators (&&, |, !, …) are for logic statements. There is no reason to write the second if statement for efficiency and semantic reasons.

Now, to be fair, the instructors must have mentioned this to let the students know why a program was crashing with the second version and why they should stick to the first version. I asked one of the students if they gave any scenario in which the bitwise operations would be used, and I was told that they didn’t give any examples.

So, the students are seeing the bitwise operations and are left with a sense that they should never use them in an if statement and therefore are pointless additions to the Java language. Never to be used and only to confuse you when you use & instead of &&.