-1

We know that All string literals in Java programs, such as "abc", are implemented as instances of String class and all this goes to String Constant Pool. my question is : where the "Hello" literal will store in below case?

String str=new String("Hello");

if this literal will goes to "String Constant Pool" then what intern method will do?

2787184
  • 3,749
  • 10
  • 47
  • 81

2 Answers2

1

String literals in your code go directly to the Sring pool. Calling intern() on them will do nothing. intern() will only make sense in cases where you are dinamically constructing Strings (in runtime, not compile-time). In those cases calling intern() will instruct the JVM to move this variable into the String pool for future usage.

Gergely Bacso
  • 14,243
  • 2
  • 44
  • 64
0

It will store into Heap. If you will use intern method then it will be pushed to String pool.

public static void main(String[] args) {
    String strLiteral="Hello";
    String str=new String("Hello");
    System.out.println(str==strLiteral);

    String str2=new String("Hello").intern();
    System.out.println(str2==strLiteral);

}



Output:-
   false
   true

1) Look at the code above, I have created a String Literal Hello, which is stored in String Pool.
2) Now I have created a String object str, if I check the references str and strLiteral they are not equal i.e. they are pointing to two different objects one in heap and other one in String pool.
3) Now I have created a String object str2 and called an intern method on it, JVM now will search the for "Hello" in String pool and return the reference to it. So now if I am checking strLiteral and str2 are equal i.e. pointing to the same object in String pool.

Amit Bhati
  • 5,569
  • 1
  • 24
  • 45
  • in above case, str refer to object of String. not the literal reference "Hello". – 2787184 Aug 19 '15 at 13:53
  • In first case two objects are getting created whereas in second case only one. Edited my answer, check. – Amit Bhati Aug 19 '15 at 13:55
  • @Thanks Amit for response. String str=new String("Hello"); in this case two Object are created, one in heap and one is in String Constant Pool. and String str2=new String("Hello").intern(); in this case only object created in String Constant Pool and return reference to str2. is my understanding is right? – 2787184 Aug 19 '15 at 14:00