D.Doi D.Doi - 2 months ago 14
Java Question

Java Confused - Primitive and Referenced

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 strange!

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

Answer
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.

Comments