-5

Java operator == is used for reference comparison

then how can == be used for comparing int a =1; and int b = 1;

both values are stored in different locations then how it compares

  • 2
    It is not just used for comparing references: as described in [JLS](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.21), it is a numerical equality operator, a boolean equality operator *and* a reference equality operator. – Andy Turner Jul 20 '16 at 07:34
  • Not actually a duplicate of the one I just marked (reopened); but you should read http://stackoverflow.com/q/8790809/3788176. – Andy Turner Jul 20 '16 at 07:37
  • primitive values don't have a location, they only have a value. – Peter Lawrey Jul 20 '16 at 08:04

1 Answers1

0

As commented by Andy, the JLS states that the operator '==' is indeed used for reference type comparison but also for numeric type and Boolean type comparison.

int is a numeric type.
When comparing numeric types the values are compared (not the references).

However if you want to determine if the references of two integers are equal rather than the values then you can use the Integer class. This class simply wraps the primitive numeric type int.

Now consider the following code:

public class TestClass {

public static void main(String[] args)
{
    Integer A = new Integer(1);
    Integer B = new Integer(1);
    Integer C = A;

    if (A == B) System.out.println("Won't print."); // (1)

    if (A.equals(B)) System.out.println("WILL Print!!!"); // (2)

    if (A == C) System.out.println("WILL Print!!!"); // (3)
}
}
  1. Because A and B are objects, the reference of A is compared to the reference of B. Even though their int values are the same, because they are independent references this statement is false.
  2. The equals method compares the int values of each Integer object and thus is true.
  3. Integer object C references object A. Hence this reference comparison will be true.