|
|
Operators and Assignments - Comparison Operators
- used to compare primitive types and object references
- organized into three subgroups: relational, equality and the instanceof operator
Relational operators ( < <= > >= )
(JLS §15.20.1)
- produce a boolean result
- work with integers and floating-point numbers
- binary numeric promotion rules apply for numeric types
- any relational expression with NaN is false
- positive and negative zero are considered equal therefore
-0.0 < 0.0 is false and -0.0 <= 0.0 is true
This is not true for Math.min() and Math.max(), which treats -0.0 as being strictly smaller than 0.0
- results, otherwise, are the same as their mathematical equivalents
Less than: 5 < 6 true
Less than or equal to: 5 <= 5 true
Greater than: 5 > 6 false
Greater than or equal to: 5 >= 5 true
Less than: -0.0 < 0.0 false
Less than or equal to: -0.0 <= 0.0 true
Greater than: 5 > NaN false
Equality operators (== != ) (JLS § 15.21)
- produce a boolean result
- lower precedence than the relational operators
- are used to compare primitive types, including boolean, and object references
- binary numeric promotion rules apply for numeric types
- if either operand is a Nan the result is false for == but true for !=
- -0.0 and 0.0 are considered equal
- if the operands are object references, the result is true if both refer to the same object or array or if both are null
- if the operands are String objects, the result is false unless they refer to the same String object, even if the two objects contain the same characters (to compare the characters in a String object use the String.equals() method) (see String Literals)
Equals: 5 == 5.0 true
Not Equal: 5 != 5.0 false
Equals: arr1 == arr2 false [different array objects]
Equals: arr1 == arr3 true [ref to same array object]
Not Equal: arr1 != arr2 true
Not Equal: arr1 != arr3 false
Equals: s1 == s2 true [same literal]
Equals: s1 == s3 true [same object reference]
Equals: s1 == s4 false [s4 is new object]
instanceof Type Comparison Operator (JLS §15.20.2, JJ pg 60)
- left-operand must be a reference object or null; cannot use primitive types
- right-operand must be a Class, Interface name or Array type
- determines if the left-operand is an instance of the class, interface or array type specified by the right-operand
- returns the boolean value true if:
- left-operand is a class or subclass of the right-operand
- left-operand is an interface or subinterface of the right-operand
- left-operand is an array of the same class, subclass or interface, subinterface of the right-operand array type
arr instanceof String[] -> true // arr = array of Strings
myNull instanceof Object -> false // null is not an object
arr1 instanceof int[] -> true // arr1 is an arry of int
Example Code
|