• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

"new Integer("5")" creates a fresh object & not utilizing the pool- like strings pool

 
Firas Zuriekat
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Tester {
public static void main (String[] args) {
int x = 5;
Integer x1 = x; Integer x2 = x;
int x3 = new Integer(5);
int x4=new Integer("5");
System.out.print(x1.equals(x));
System.out.print(x1 == x);
System.out.print(x2.equals(x1));
System.out.print(x2 == x1);
System.out.print(x2 == x3);
System.out.print(x2.equals(x3));
System.out.print(x4==x3);
// x4, x3 aren't in the pool because of "new" was used to create a fresh objects. So why this prints "true"?
}
}

OUTPUT: truetruetruetruetruetruetrue

So why "new" here doesn't create a new object for x3 and x4? ("true" printed for all!!!)
[ May 31, 2006: Message edited by: Firas Zureikat ]
 
wise owen
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
x3 and x4 are primtive data type.
 
Firas Zuriekat
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you...I just noticed....It's so important to look really close on the code :-)
 
Amirr Rafique
Ranch Hand
Posts: 324
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the concept of pooling in primitives. Any one please explain
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is what the Java Language Specification says.

If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic