The == and != operators are binary operators that evaluate to true or false depending on whether the operands are equal. The == operator gives true if the operands are equal and false otherwise. The != operator gives false if the operands are equal and true otherwise.
These operators can be used operands with primitive and reference types, but the behavior is significantly different. According to the JLS, there are actually three distinct sets of these operators:
However, in all cases, the result type of the == and != operators is boolean.
The Numeric == and != operators
When one (or both) of the operands of an == or != operator is a primitive numeric type (byte, short, char, int, long, float or double), the operator is a numeric comparison. The second operand must be either a primitive numeric type, or a boxed numeric type.
The behavior other numeric operators is as follows:
Note : you need to be careful when using == and != to compare floating point values.
The Boolean == and != operators
If both operands are boolean, or one is boolean and the other is Boolean, these operators the Boolean == and != operators. The behavior is as follows:
A | B | A == B | A != B |
---|---|---|---|
false | false | true | false |
false | true | false | true |
true | false | false | true |
true | true | true | false |
There are two "pitfalls" that make it advisable to use == and != sparingly with truth values:
The Reference == and != operators
If both operands are object references, the == and != operators test if the two operands refer to the same object. This often not what you want. To test if two objects are equal by value, the .equals() method should be used instead.
String s1 = "We are equal"; String s2 = new String("We are equal"); s1.equals(s2); // true // WARNING - don't use == or != with String values s1 == s2; // false
Warning: using == and != to compare String values is incorrect in most cases; see http://stackoverflow.com/documentation/java/4388/java-pitfalls/16290/using-to-compare-strings . A similar problem applies to primitive wrapper types; see http://stackoverflow.com/documentation/java/4388/java-pitfalls/8996/using-to-compare-primitive-wrappers-objects -such-as-integer .
From Java 8 onwards, the Lambda operator ( -> ) is the operator used to introduce a Lambda Expression. There are two common syntaxes, as illustrated by these examples:
Version ≥ Java SE 8 a -> a + 1 // a lambda that adds one to its argument a -> { return a + 1; } // an equivalent lambda using a block.
A lambda expression defines an anonymous function, or more correctly an instance of an anonymous class that implements a functional interface.
(This example is included here for completeness. Refer to the Lambda Expressions topic for the full treatment.)
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions