Java Reference
In-Depth Information
> : greater than
>= : greater than or equal
The relational operators can only be performed on numeric primitive types, and the
result of each relational operator is always a boolean . If the operands are not the same
primitive type, the smaller operand is promoted to the larger operand's type before the
comparison is made.
To demonstrate the relational operators, let's take a look at some examples. What is the
result of the following statements?
5. int x = 10, y = 20, z = 10;
6. System.out.println(x < y);
7. System.out.println(x <= y);
8. System.out.println(x > z);
9. System.out.println(x >= z);
Because x and z are the same value, x > z is false . The other statements evaluate to
true . Therefore, the output of this code is
true
true
false
true
The boolean Primitive Type
The result of a relational operator is a boolean , which can only be the values true or
false . The following line of code does not compile:
int result = x < y;
The boolean primitive type in Java is not compatible with the int type. In other
languages like C and C++, numeric types are often used for Boolean expressions, where
0 is false and non-zero is true. In Java, a boolean can never be treated as a numeric type,
nor can a numeric type ever be treated as a true or false value.
The instanceof Operator
The instanceof operator compares a reference to a class or interface data type. The result
is true if the reference is an instance of the data type; otherwise, the result is false . The
syntax for the instanceof operator looks like this:
reference instanceof ClassOrInterfaceName
Search WWH ::




Custom Search