A more general rule is to not make code more complicated than it need to be.
int shirt = (int)(Math.random() * 10); // shirt numbers from 0 to 9.
if(shirt == 1)
System.out.println("It's 1!");
else
System.out.println(shirt);
This illustrated that ==
can be used to compare primitives. It can also be used to compare references, but not to compare the contents of objects.
Double d = 0.1;
Double e = 0.1;
System.out.println("(Double) 0.1 == (Double) 0.1 is " + (d == e));
double x = 0.1;
double y = 0.1;
System.out.println("0.1 == 0.1 is " + (x == y));
prints
(Double) 0.1 == (Double) 0.1 is false
0.1 == 0.1 is true
This shows that when comparing Double
, like Strings, objects ==
doesn't compare contents.
One confusion in all this when a cache is used, as is the case for String literals. This means that values which are referenced in different places actually use the same object for performance reasons.
Integer d = 10;
Integer e = 10;
System.out.println("(Integer) 10 == (Integer) 10 is " + (d == e));
int x = 10;
int y = 10;
System.out.println("10 == 10 is " + (x == y));
prints
(Integer) 10 == (Integer) 10 is true
10 == 10 is true
The first example works because Java 5.0+ uses a cache of small integers. (The size of a small integer varies depending on command line parameters :} )
Integer d = -129;
Integer e = -129;
System.out.println("(Integer) -129 == (Integer) -129 is " + (d == e));
int x = -129;
int y = -129;
System.out.println("-129 == -129 is " + (x == y));
prints
(Integer) -129 == (Integer) -129 is false
-129 == -129 is true
As for strings, a string literal cache is used. Also the compiler will simplify constant expressions so strings written a different way can be the same.
final int one = 1;
int oneB = 1;
String a = "1";
String b = "" + 1;
String c = "" + one;
String d = "" + oneB;
System.out.println(a == b);
System.out.println(a == c);
System.out.println(a == d);
prints
true
true
false
The contents of each strings is the same, but oneB
is not a constant, so the expression is evaluated at runtime and a different string is produced.
IMHO: Java attempts to hide details from developers and it would have been a better choice to make ==
call equals
whereas you could have an operator ===
if you really wanted to compare actual references .