Thursday, February 5, 2015

equals vs ==

If equals method is used to compare Object type and primitive type variables, some wrong results could be occurred which are shown below as yellow color. If == operator is used there is no problem.

If you want to be sure if the comparison is right, the best way is to convert all variables into same data type.


Example 1:
Integer i = 5;
short s = 5;

System.out.println(i.equals(s)); false
System.out.println(i.equals(5)); true
System.out.println(i == 5); true
System.out.println(i == s); true


Example 2:
Long l = 5L;
int i = 5;

System.out.println(l.equals(i)); false
System.out.println(l.equals(5)); false
System.out.println(l.equals(5L)); true
System.out.println(l == 5); true
System.out.println(l == 5L); true
System.out.println(l == i); true


Example 3:
Short s1 = 5;
short s2 = 5;

System.out.println(s1.equals(s2)); true
System.out.println(s1.equals(5)); false
System.out.println(s1 == 5); true
System.out.println(s1 == s2); true

No comments:

Post a Comment