Thursday 7 December 2006

SCJP Chapter 4

A nice small focused chapter on operators. It starts with the assignment operator "=" and its compound kin (+=, -=, *=,/=). With the compound operators, the right side of the = will always be evaluated first, something to take note of.

Relational operators (<, <=, >, >=, == and !=) are relatively straightforward. Comparison of characters use their Unicode value. Equality (==) for objects only check whether variables point to the same object, not whether two objects are the same.

The instanceof operator is used with object reference variables and checks for type. It returns true if the variable IS-A particular class (or superclass) or interface (indirectly or directly implemented). It is legal to test null eg. null instanceof String, but it will always return false. It will not compile if testing a class with no relationship to the other class eg. Dog instanceof Cat. Last note: array IS-A Object.

Arithmetic operators (+, -, *, /, %) are simple to understand. The remainder operator (%) divides two operands and returns the remainder as the result. The + operator can be used to concatenate strings and care must be taken to verify which role it is in. If either one of the operands are strings then it concatenates, otherwise it is a normal addition operator.

Increment and decrement operators (++ and --) have two modes, prefix and postfix. Below shows a code example. These operators can not be used on final variables, doing so results in a compiler error.

int x = 1;

if(++x == 2) // prefix, x is incremented to 2 and
{ return true; }// the expression is evaluated,
// returning true

if(x++ == 2) // postfix, the expression is
{ return true; }// evaluated first, returning true
// then x is incremented to 3

The conditional operator is a ternary operator (with three operands). It is a miniature if statement. The structure is as below.

x = (boolean expression) ? value if true : value if false

Logical operators (&, |, ^, !, &&, ||) are the last topic in the chapter. Short-circuit operators (&& and ||) evaluate up to the operand they need to make a conclusive decision. AND (&&) will return false upon the first operand resolving to false, and does not bother to check any other operands after that. Similarly, OR (||) will return true for the first operand resolving to true.
The non-short-circuit operators (& and |) evaluate all the operands. This is a key point to remember. XOR (^) returns true when EXACTLY one operand is true. The ! operator returns the opposite of the boolean value.

Onto chapter 5, where flow control rules.

No comments: