Is nullcheck needed before using instanceof?

A question that I have come across every now and then is if it’s necessary to check if a variable is null (or not null) before calling instanceof operator, or calling the isInstance() method of a Class to avoid NullPointerException.

No, that is not necessary. The code below shows an example calling instanceof with both a non-null String and a null String.

The output from the code is:

The instanceof operator

The instanceof operator is used to check whether an object belongs to a certain class.
In other words, it is only used on reference types, not on primitive types (but it can be used on primitive types wrapper classes).
The left operand of the expression is the reference to the object to check, and the right operand is the class name.

Continue reading

Bitwise and shift operators

These operators are low-level operators that are used on integer and long values. They are used to either test for bits or change the value of certain bits in a number.
The bitwise and shift operators can only be used with integer numbers, not floating-point numbers. Bitwise operators can be used with booleans and then they evaluate both expressions regardless of the value of the first one.

If either of the arguments to a bitwise operator is a long, the result is a long. Otherwise, the result is an int. If the left operand of a shift operator is a long, the result is a long – otherwise, the result is an int.

Continue reading

Increment and Decrement operators

Incremental operator

The incremental operator ++ increments a value by one.
The value may be a property of an object, an element of an array containing numbers or a variable.

The ++ operator can be positioned before or after the operand on which it operates.
If it is positioned before the operand, that operand is incremented before it is used in a possible expression.
Likewise, if it’s positioned after the operand, the expression is evaluated before the increment is being done.

A couple of examples:

Continue reading