JVM Knowledge

The numerical comparison operators <, >, <=, and >=, and the instanceof operator, are called the relational operators.

RelationalExpression:
  ShiftExpression
  RelationalExpression < ShiftExpression
  RelationalExpression > ShiftExpression
  RelationalExpression <= ShiftExpression
  RelationalExpression >= ShiftExpression
  InstanceofExpression

The relational operators are syntactically left-associative (they group left-to-right).

However, this fact is not useful. For example, a<b<c parses as (a<b)<c, which is always a compile-time error, because the type of a<b is always boolean and < is not an operator on boolean values.

The type of a relational expression is always boolean.

15.20.1. Numerical Comparison Operators <, <=, >, and >=

The type of each of the operands of a numerical comparison operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs.

Binary numeric promotion is performed on the operands (§5.6).

Note that binary numeric promotion may include unboxing conversion (§5.1.8).

If the promoted type of the operands is int or long, then signed integer comparison is performed.

If the promoted type is float or double, then floating-point comparison is performed.

The result of a floating-point comparison, as determined by the specification of the IEEE 754 standard, is:

  • If either operand is NaN, then the result is false.

  • All values other than NaN are ordered, with negative infinity less than all finite values, and positive infinity greater than all finite values.

  • Positive zero and negative zero are considered equal.

    For example, -0.0<0.0 is false, but -0.0<=0.0 is true.

    Note, however, that the methods Math.min and Math.max treat negative zero as being strictly smaller than positive zero.

Subject to these considerations for floating-point numbers, the following rules then hold for integer operands or for floating-point operands other than NaN:

  • The value produced by the < operator is true if the value of the left-hand operand is less than the value of the right-hand operand, and otherwise is false.
  • The value produced by the <= operator is true if the value of the left-hand operand is less than or equal to the value of the right-hand operand, and otherwise is false.
  • The value produced by the > operator is true if the value of the left-hand operand is greater than the value of the right-hand operand, and otherwise is false.
  • The value produced by the >= operator is true if the value of the left-hand operand is greater than or equal to the value of the right-hand operand, and otherwise is false.

15.20.2. The instanceof Operator

An instanceof expression may perform either type comparison or pattern matching.

InstanceofExpression:
  RelationalExpression instanceof ReferenceType
  RelationalExpression instanceof Pattern

If the operand to the right of the instanceof keyword is a ReferenceType, then the instanceof keyword is the type comparison operator.

If the operand to the right of the instanceof keyword is a Pattern, then the instanceof keyword is the pattern match operator.

The following rules apply when instanceof is the type comparison operator:

  • The type of the expression RelationalExpression must be a reference type or the null type, or a compile-time error occurs.

  • The RelationalExpression must be checked cast compatible with the ReferenceType (§5.5), or a compile-time error occurs.

  • At run time, the result of the type comparison operator is determined as follows:

    • If the value of the RelationalExpression is the null reference (§4.1), then the result is false.
    • If the value of the RelationalExpression is not the null reference, then the result is true if the value could be cast to the ReferenceType without raising a ClassCastException, and false otherwise.

The following rules apply when instanceof is the pattern match operator:

  • The type of the expression RelationalExpression must be a reference type or the null type, or a compile-time error occurs.

  • The Pattern must be applicable at the type of the expression RelationalExpression (§14.30.3), or a compile-time error occurs.

  • At run time, the result of the pattern match operator is determined as follows:

    • If the value of the RelationalExpression is the null reference, then the result is false.

    • If the value of the RelationalExpression is not the null reference, then the result is true if the value matches the Pattern (§14.30.2), and false otherwise.

      A side effect of a true result is that all the pattern variables declared in Pattern, if any, will be initialized.

Example 15.20.2-1. The Type Comparison Operator

class Point   { int x, y; }
class Element { int atomicNumber; }
class Test {
    public static void main(String[] args) {
        Point   p = new Point();
        Element e = new Element();
        if (e instanceof Point) {  // compile-time error
            System.out.println("I get your point!");
            p = (Point)e;  // compile-time error
        }
    }
}

This program results in two compile-time errors. The cast (Point)e is incorrect because no instance of Element or any of its possible subclasses (none are shown here) could possibly be an instance of any subclass of Point. The instanceof expression is incorrect for exactly the same reason. If, on the other hand, the class Point were a subclass of Element (an admittedly strange notion in this example):

class Point extends Element { int x, y; }

then the cast would be possible, though it would require a run-time check, and the instanceof expression would then be sensible and valid. The cast (Point)e would never raise an exception because it would not be executed if the value of e could not correctly be cast to type Point.

Prior to Java SE 16, the ReferenceType operand of a type comparison operator was required to be reifiable (§4.7). This prevented the use of a parameterized type unless all its type arguments were wildcards. The requirement was lifted in Java SE 16 to allow more parameterized types to be used. For example, in the following program, it is legal to test whether the method parameter x, with static type List<Integer>, has a more "refined" parameterized type ArrayList<Integer> at run time:

import java.util.ArrayList;
import java.util.List;

class Test2 {
    public static void main(String[] args) {
        List<Integer> x = new ArrayList<Integer>();

        if (x instanceof ArrayList<Integer>) {  // OK
            System.out.println("ArrayList of Integers");
        }
        if (x instanceof ArrayList<String>) {  // error
            System.out.println("ArrayList of Strings");
        }
        if (x instanceof ArrayList<Object>) {  // error
            System.out.println("ArrayList of Objects");
        }
    }
}

The first instanceof expression is legal because there is a casting conversion from List<Integer> to ArrayList<Integer>. However, the second and third instanceof expressions both cause a compile-time error because there is no casting conversion from List<Integer> to ArrayList<String> or ArrayList<Object>.