Posts Tagged ‘comparisons’

Comparisons in Java

When comparing objects, it is useful to know the difference between  == and the equals() method.

The == comparsion is used to compare the values of two objects to see if they refer to the same object.  Note there are 8 primitives in Java:  boolean, byte, char, double, float, int, long, and short. In the example below, you will see why a String comparison will not work for the == comparison. This is because the == comparison is used as an equality operator to compare two like primitive values.

Ex 1:

if( a == "abc")  // FALSE

Ex 2:

String a = "abc";
String b = "abc";
if(a == b) // FALSE because they are two separate String objects

Ex 3:

int i = 1;
int j = 1;
if( i == j)  // TRUE

The equals() method is used to compare two object values to see if they are identical. This method is not used on primitive values.

For example,

String name = "abc";
if(name.equals("abc")) // TRUE