0
String str = "Hello";

str = "Hello";

Above statements will create two objects on heap or same object will be return by jvm? Thanks in advance

Ravi Mengar
  • 1,181
  • 1
  • 11
  • 18
sanil
  • 482
  • 1
  • 7
  • 23
  • `"Hello"` is a constant in the `String` pool. Only one object is involved here. – Elliott Frisch Nov 12 '19 at 07:24
  • https://www.journaldev.com/797/what-is-java-string-pool this article can help in understanding how does string works. – George Weekson Nov 12 '19 at 07:26
  • When you use double quotes to create a String, it first looks for String with the same value in the String pool, if found it just returns the reference else it creates a new String in the pool and then returns the reference. So, here only one object will be created by jvm. – Ravi Mengar Nov 12 '19 at 07:40
  • *At most* one object, as there could already be an existing string before the execution of this code. – Holger Nov 12 '19 at 15:48

2 Answers2

0

String str = "Hello" it will go to SCP memory. like str pointing to your String variable"hello". there is only one object.

Omkar SJ
  • 1
  • 1
0

String literals are stored in the SpringPool.

In your above example, "Hello" is a string pool and there will be only one reference of this object in the string pool. Hence there will be only one object in the memory.

Lal Mohandas
  • 116
  • 5