• No results found

The Instanceof Operator

In document JavaNotesForProfessionals.pdf (Page 91-95)

This operator checks whether the object is of a particular class/interface type. instanceof operator is written as:

( Object reference variable ) instanceof (class/interface type)

Example:

public class Test {

public static void main(String args[]){

String name = "Buyya";

// following will return true since name is type of String boolean result = name instanceof String;

System.out.println( result );

} }

This would produce the following result:

true

This operator will still return true if the object being compared is the assignment compatible with the type on the right.

Example:

class Vehicle {}

public class Car extends Vehicle {

public static void main(String args[]){

Vehicle a = new Car();

boolean result = a instanceof Car;

System.out.println( result );

} }

This would produce the following result:

true

Section 13.8: The Assignment Operators (=, +=, -=, *=, /=, %=,

<<=, >>= , >>>=, &=, |= and ^=)

The left hand operand for these operators must be a either a non-final variable or an element of an array. The right hand operand must be assignment compatible with the left hand operand. This means that either the types must be the same, or the right operand type must be convertible to the left operands type by a combination of boxing, unboxing or widening. (For complete details refer to JLS 5.2.)

The precise meaning of the "operation and assign" operators is specified by JLS 15.26.2 as:

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

Note that there is an implicit type-cast before the final assignment.

1.

=

The simple assignment operator: assigns the value of the right hand operand to the left hand operand.

Example: c = a + b will add the value of a + b to the value of c and assign it to c

2. +=

The "add and assign" operator: adds the value of right hand operand to the value of the left hand operand and assigns the result to left hand operand. If the left hand operand has type String, then this a "concatenate and assign" operator.

Example: c += a is roughly the same as c = c + a

3. -=

The "subtract and assign" operator: subtracts the value of the right operand from the value of the left hand operand and assign the result to left hand operand.

Example: c -= a is roughly the same as c = c - a

4. *=

The "multiply and assign" operator: multiplies the value of the right hand operand by the value of the left hand operand and assign the result to left hand operand. .

Example: c *= a is roughly the same as c = c * a

5. /=

The "divide and assign" operator: divides the value of the right hand operand by the value of the left hand operand and assign the result to left hand operand.

Example: c /*= a is roughly the same as c = c / a

6. %=

The "modulus and assign" operator: calculates the modulus of the value of the right hand operand by the value of the left hand operand and assign the result to left hand operand.

Example: c %*= a is roughly the same as c = c % a

7. <<=

The "left shift and assign" operator.

Example: c <<= 2 is roughly the same as c = c << 2

8. >>=

The "arithmetic right shift and assign" operator.

Example: c >>= 2 is roughly the same as c = c >> 2

9. >>>=

The "logical right shift and assign" operator.

Example: c >>>= 2 is roughly the same as c = c >>> 2

10. &=

The "bitwise and and assign" operator.

Example: c &= 2 is roughly the same as c = c & 2

11. |=

The "bitwise or and assign" operator.

Example: c |= 2 is roughly the same as c = c | 2

12. ^=

The "bitwise exclusive or and assign" operator.

Example: c ^= 2 is roughly the same as c = c ^ 2

Section 13.9: The conditional-and and conditional-or Operators ( && and || )

Java provides a conditional-and and a conditional-or operator, that both take one or two operands of type boolean and produce a boolean result. These are:

&& - the conditional-AND operator,

|| - the conditional-OR operators. The evaluation of <left-expr> && <right-expr> is equivalent to the following pseudo-code:

{

boolean L = evaluate(<left-expr>);

if (L) {

return evaluate(<right-expr>);

} else {

// short-circuit the evaluation of the 2nd operand expression return false;

} }

The evaluation of <left-expr> || <right-expr> is equivalent to the following pseudo-code:

{

boolean L = evaluate(<left-expr>);

if (!L) {

return evaluate(<right-expr>);

} else {

// short-circuit the evaluation of the 2nd operand expression return true;

} }

As the pseudo-code above illustrates, the behavior of the short-circuit operators are equivalent to using if / else statements.

Example - using && as a guard in an expression

The following example shows the most common usage pattern for the && operator. Compare these two versions of a method to test if a supplied Integer is zero.

public boolean isZero(Integer value) { return value == 0;

}

public boolean isZero(Integer value) { return value != null && value == 0;

}

The first version works in most cases, but if the value argument is null, then a NullPointerException will be thrown.

In the second version we have added a "guard" test. The value != null && value == 0 expression is evaluated by first performing the value != null test. If the null test succeeds (i.e. it evaluates to true) then the value == 0 expression is evaluated. If the null test fails, then the evaluation of value == 0 is skipped (short-circuited), and we don't get a NullPointerException.

Example - using && to avoid a costly calculation

The following example shows how && can be used to avoid a relatively costly calculation:

public boolean verify(int value, boolean needPrime) { return !needPrime | isPrime(value);

}

public boolean verify(int value, boolean needPrime) { return !needPrime || isPrime(value);

}

In the first version, both operands of the | will always be evaluated, so the (expensive) isPrime method will be called unnecessarily. The second version avoids the unnecessary call by using || instead of |.

Section 13.10: The Relational Operators (<, <=, >, >=)

The operators <, <=, > and >= are binary operators for comparing numeric types. The meaning of the operators is as you would expect. For example, if a and b are declared as any of byte, short, char, int, long, float, double or the corresponding boxed types:

- `a < b` tests if the value of `a` is less than the value of `b`.

- `a <= b` tests if the value of `a` is less than or equal to the value of `b`.

- `a > b` tests if the value of `a` is greater than the value of `b`.

- `a >= b` tests if the value of `a` is greater than or equal to the value of `b`.

The result type for these operators is boolean in all cases.

Relational operators can be used to compare numbers with different types. For example:

int i = 1;

long l = 2;

if (i < l) {

System.out.println("i is smaller");

}

Relational operators can be used when either or both numbers are instances of boxed numeric types. For example:

Integer i = 1; // 1 is autoboxed to an Integer Integer j = 2; // 2 is autoboxed to an Integer if (i < j) {

System.out.println("i is smaller");

}

The precise behavior is summarized as follows:

If one of the operands is a boxed type, it is unboxed.

1.

If either of the operands now a byte, short or char, it is promoted to an int. 2.

If the types of the operands are not the same, then the operand with the "smaller" type is promoted to the 3.

"larger" type.

The comparison is performed on the resulting int, long, float or double values.

4.

You need to be careful with relational comparisons that involve floating point numbers:

Expressions that compute floating point numbers often incur rounding errors due to the fact that the computer floating-point representations have limited precision.

When comparing an integer type and a floating point type, the conversion of the integer to floating point can also lead to rounding errors.

Finally, Java does bit support the use of relational operators with any types other than the ones listed above. For example, you cannot use these operators to compare strings, arrays of numbers, and so on.

In document JavaNotesForProfessionals.pdf (Page 91-95)