The equals() method of the Short class is used to compare a Short object with another object for equality. It returns true when the specified object is also a Short object and contains the same short value as the object on which equals() is called. Otherwise, it returns false.
- It compares the value of two Short objects.
- The argument must refer to a Short object with the same value for the method to return
true.
class GFG {
public static void main(String[] args)
{
// creating a Short object
Short a = new Short("20");
// creating a Short object
Short b = new Short("20");
// equals method in Short class
boolean output = a.equals(b);
// Printing the output
System.out.println("Does " + a
+ " equals " + b
+ " : " + output);
}
}
Output
Does 20 equals 20 : true
Explanation: Both a and b are Short objects containing the value 20. Therefore, a.equals(b) returns true.
Syntax
public boolean equals(Object obj)
Parameters: obj â the object to be compared with the current Short object.
Return Value
- Returns true if obj is a Short object with the same value.
- Returns false otherwise.
Example: Comparing Different Short Values
class GFG {
public static void main(String[] args)
{
// creating a Short object
Short a = new Short("2");
// creating a Short object
Short b = new Short("20");
// equals method in Short class
boolean output = a.equals(b);
// Printing the output
System.out.println("Does " + a
+ " equals " + b
+ " : " + output);
}
}
Output
Does 2 equals 20 : false
Explanation: The values of a and b are different. Therefore, a.equals(b) returns false.
Example: Comparing Short with Another Data Type
public class Main {
public static void main(String[] args) {
Short a = Short.valueOf((short) 20);
Integer b = 20;
boolean result = a.equals(b);
System.out.println("Result: " + result);
}
}
Output
Result: false
Explanation: a is a Short object, while b is an Integer object. Since the objects are of different wrapper types, equals() returns false.
Difference Between equals() and == for Short
| Feature | equals() | == |
|---|---|---|
| Comparison | Compares values of Short objects | Compares references when both operands are objects |
| Return Type | boolean | boolean |
| Wrapper Objects | Checks logical equality | Checks whether references refer to the same object |
| Recommended For | Comparing Short values | Comparing object identity |