1

When we create String in JAVA.

String s = new String("hello"); 

This s object is created in a Heap. While

String s = "hello";

which is stored in String pool.

Similarly for the Integer class,

Integer i = new Integer(10); // Created in Heap.

or

Integer  ii = 10;  // Where is this created? Why I have never heard of Integer pool?
Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Raj
  • 692
  • 2
  • 9
  • 23
  • 1
    There is indeed a pool with Integers in, just not all of them. Read http://stackoverflow.com/q/20877086/1081110 – Dawood ibn Kareem Mar 20 '14 at 08:24
  • I'm not sure about the specifics, but aren't the integers from -127 to 128 cached somewhere? – skiwi Mar 20 '14 at 08:25
  • 1
    possible duplicate of [Java Integer: Constant Pool](http://stackoverflow.com/questions/13098143/java-integer-constant-pool) – D.R. Mar 20 '14 at 08:26
  • Give this a read: http://stackoverflow.com/questions/93091/why-cant-strings-be-mutable-in-java-and-net – Sudarshan_SMD Mar 20 '14 at 08:29

2 Answers2

1

About Integer:

Better always use

Integer i = Integer.valueOf(42)

An explanation for the why can be found in the Javadoc comment for this method:

This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.

About String:

Strings are not only used by programmers (such as you). They are also heavily used by the JVM itself. All declarations are also simple Strings. The compiled byte code is full of them. The String pool can be considered as the JVM's chache mechanism for all those Strings.

A programmer is also able to use this String pool with the String.intern() method.

Seelenvirtuose
  • 20,273
  • 6
  • 37
  • 66
0

Because the flyweight design pattern makes no sense for integers in general - they are mostly not used as constants but as mutable values.

There are some predefined Integer values where it makes sense: like ZERO or ONE. Also an Integer is put into the pool if it is used as a constant.

Edit: just realized that the answer in Why does the behavior of the Integer constant pool change at 127? is better.

Community
  • 1
  • 1
D.R.
  • 20,268
  • 21
  • 102
  • 205