0
String str=new String ("xyz");

I read somewhere JVM create 2 object 1st in pool and 2nd in heap.

Is this true ? If true then why JVM create 2 object when one is already there can anyone explain?

PM 77-1
  • 12,933
  • 21
  • 68
  • 111
Amol Nalge
  • 11
  • 2
  • you are using the new keyword.... that is going to the heap... not the string pool – ΦXocę 웃 Пepeúpa ツ Nov 20 '17 at 19:22
  • It's true, and it's true because you told it to do that. – Louis Wasserman Nov 20 '17 at 19:24
  • @LouisWasserman my question is why 2 objects are created by JVM – Amol Nalge Nov 20 '17 at 19:31
  • Because the JVM needed to have an object for `"xyz"`, and then you _told it_ to create another object, a copy of that. – Louis Wasserman Nov 20 '17 at 19:33
  • The pool is irrelevant. Both `String` instances are stored in the heap, simply because that’s how the term “heap” is defined in the Java programming language, the storage space of all Java objects. The string pool only contains *references* to string instances. But behind the scenes, there is at least one array holding the actual character data and in Java, arrays are objects too. Depending on the JRE version, there might be even two arrays, but in recent JREs, the array is shared between both strings. – Holger Nov 21 '17 at 10:43
  • @Holger *The string pool only contains references to string instances*.. how come? why is everyone drawing `"abc"` for example inside a circle and say that this *is* the contents of the constant pool? Or have I miss-understood you here? – Eugene Nov 21 '17 at 16:50
  • @Eugene: people love drawings and like to spread them if they look nice and convincing, while at the same time they don’t love technical details. Such a graphic may even be semantically correct, as long as it doesn’t claim that the pool was outside the heap, as you can can consider all string instances referenced by the pool to form a set (i mean [this kind of set](https://en.wikipedia.org/wiki/Set_theory)) and draw a circle around them. But technically, the membership does not imply any property regarding the storage of the string instances. It’s like adding a Java object to a `HashSet`… – Holger Nov 21 '17 at 17:38

2 Answers2

1

Yes, you are right. It creates two objects. One in String Constant Pool and another object in Heap pointing to the String pool.

  1. If we consider String str= "Hello" //String literal, it creates only one object by JVM in String Constant Pool.
  2. As per your syntax(String str = new String("xyz") //String object) JVM creates 2 objects. One in string pool and another in heap).

For further reference, please check the following discussion: String s = new String("xyz"). How many objects has been made after this line of code execute?

bdeshago
  • 11
  • 2
0

"xyz" is in the constant pool once the class has been loaded str is put on the heap when that line actually runs

see Where does Java's String constant pool live, the heap or the stack?

Sahan Jayasumana
  • 440
  • 6
  • 10