-3

Several ways of creating string are shown below. Questions are added following the expressions in the way of comments.

String str = "test";
String str1 = new String(str);  //Will it invoke the Constructor of String(String)?
String str2 = new String("test");//Will it invoke the Constructor of String(String)?
String str3 = str; //Which Constructor will it invoke? Or str3 only reference to str and "test" without being constructed?
String str4 = "test";//Which Constructor will it invoke? Or str4 only reference to str and "test" without being constructed?
String strnew = new String("testnew");//Will this expression create "testnew" in String Constant Pool before it creates strnew?

One additional question: Is there any difference bwtween the ways of creating str3 and str4?

akhilless
  • 3,169
  • 19
  • 24
Ryan
  • 213
  • 1
  • 8

1 Answers1

5

Whenever you call new in JAVA it create an object in heap and obviously it will call the constructor also.

String literals will go to String Constant Pool.

It might help you to understand it visually.

enter image description here

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
  • I have read this figure. I still have the questions shown above. Can you have a look at them? – Ryan May 08 '14 at 14:36
  • Sure. First read two lines of my post. – Braj May 08 '14 at 14:37
  • "String literals will go to String Constant Pool". So the expression "String strnew = new String("testnew")" will create "testnew" in String Constant Pool before it creates strnew? – Ryan May 08 '14 at 14:43
  • String literal `"testnew"` will go to String constant pool and `strnew` will go to heap. Look at first example of the diagram. – Braj May 08 '14 at 14:44
  • 1
    Thank you very much! And about str3 and str4, Which Constructor will it invoke? or they are just references to "test"? – Ryan May 08 '14 at 14:49
  • for `str3` and `str4` no constructor is called. They are just referencing to the existing String. – Braj May 08 '14 at 14:50
  • **Remember** constructor is called only when you called it via `new` keyword. – Braj May 08 '14 at 14:51
  • My pleasure. You're most welcome. you can remember for longer time using Visually representation most probably for your next interview :) – Braj May 08 '14 at 14:52