-1

I am little confused about some concepts in Primitive and Referenced data types ... I know the difference, but when i tried out this code, the output is unexpected!

class Learn{

public static void main(String[] args) {
    
    int a = 5;
    int b = 6;
    int c = 5;
    
    System.out.println(a);
    System.out.println(b);
    System.out.println(c);
    
    if (a == c)
        System.out.println("PE");
    
    if (b != c)
        System.out.println("PNE");
    
    System.out.println("========");
    
    Integer x = new Integer(5);
    Integer y = new Integer(6);
    Integer z = new Integer(5);
    
    System.out.println(x);
    System.out.println(y);
    System.out.println(z);
    
    if (x == z)
        System.out.println("RE");
    
    if (y != z)
        System.out.println("RNE");
}
}

and that is the output

5

6

5

PE

PNE

========

5

6

5

RNE

So why RE is not written to STDOUT like RNE?

Community
  • 1
  • 1
D.Doi
  • 17
  • 1

3 Answers3

2
Integer x = new Integer(5);
Integer y = new Integer(6);
Integer z = new Integer(5);

x and z refer to different Integer objects (since each type you use the new keyword, you are creating a unique object). Therefore x==z is false. x.equals(z) would return true, since both objects contain the same numeric value.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

Because when you are comparing x and z, you are actually comparing the Objects, not the the value they contain.

Venom
  • 19
  • 3
0

x and z refer to different Integer objects. When you compare x == y, you are comparing object references.

On the other hand, a, b, c are value types, so when you compare a == c, then their values will be compared.

SusanW
  • 1,550
  • 1
  • 12
  • 22
Farhan Yaseen
  • 2,507
  • 2
  • 22
  • 37