Java - AutoBoxing/Unboxing and == operator

== operator and the autoboxing rules.

If both operands are primitive types, they are compared as primitive types using a value comparison.

If both operands are reference types, their references are compared.

In the two cases above, no autoboxing/unboxing is needed.

When one operand is a reference type and another is a primitive type, the reference type is unboxed to a primitive type and a value comparison takes place.

Consider the following code. It is an example of using both primitive type operands for the == operator.

Demo

public class Main {
  public static void main(String[] args) {
    int a = 100;/*from ww w .  j  a v  a  2s .  c  o  m*/
    int b = 100;
    int c = 505;
    System.out.println(a == b); // will print true
    System.out.println(a == c); // will print false

  }
}

Result

Consider the following snippet of code: no autoboxing/unboxing takes place.

aa == bb and aa == cc compare the references of aa, bb and cc, not their values.

Every object created with the new operator has a unique reference.

Demo

public class Main {
  public static void main(String[] args) {
    Integer aa = new Integer(100);
    Integer bb = new Integer(100);
    Integer cc = new Integer(505);
    System.out.println(aa == bb); // will print false
    System.out.println(aa == cc); // will print false
  }//from w w w .j ava  2 s. c o  m
}

Result

Related Topic