• Post Reply Bookmark Topic Watch Topic
  • New Topic

Output of this code snippet  RSS feed

 
abin joy
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
code
--------------------------
Integer i1=1000;
Integer i2=1000;
Integer i3=10;
Integer i4=10;
if(i1!=i2) {
System.out.println("diff objects");
}
if(i3==i4{
System.out.println("same objects");
}
}

code
--------------------------
produces the output
diff objects
same objects

Why is != telling us that i1 and i2 are different objects, when = = is saying that i3 and i4 are the same object?
 
Tony Fu
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Although i don't know the reason,I guess the left of "=",is the type of short.If i3 = 128 and i4 = 128 ,the result is diff object.
Maybe it helps you!!
 
Gamini Sirisena
Ranch Hand
Posts: 378
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check this code.. run it with the argument 140

 
Sagar Rohankar
Ranch Hand
Posts: 2907
1
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Like String constant pool, The Integer have its own pool of integers from -128 to 127 , and above this number an object is created ! Thats why your getting this output !

This links best explains your doubt !!
 
pradeepta chopra
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
is it also applies to Float objects??
i ran the above code with Float objects but got different objects for all values??
so,only String and Integer pools seem to exist :roll:
 
Vijitha Kumara
Bartender
Posts: 4002
42
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

pradeepta chopra:
so,only String and Integer pools seem to exist


try with Byte
 
Ankit Garg
Sheriff
Posts: 9610
37
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The pool exists for Byte, Short, Integer and Strings.
 
Brij Garg
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also for Booleans and Characters(\u0000 to \u007f)
 
Paul Beckett
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just to add: the pool is only used when autoboxing

 
Ankit Garg
Sheriff
Posts: 9610
37
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Paul Beckett:
Just to add: the pool is only used when autoboxing


This is because when autoboxing the compiler inserts Type.valueOf(primitiveValue); istead of new Type(primitiveValue);
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!