1

I know that

String s1 = "test";
String s2 = new String("test");
System.out.println(s1==s2);  // false

in above snippet "test" String Object is created inside the String pool in java (s1 will be passed its reference) and a new String Object will be created in the heap space of the memory (s2 will be in heap sapce).

so will s2 String object be referring to the String pool's "test" String object internally or s2 keeps an altogether different "test" String Object in memory ?

what will be the effect if we somehow "test" String Object in String constant pool is removed ? will s2 still be having the value "test" ?

I know this topic has been touched a lot but none of the previous answers which i checked clarifies it.

please mention any sources if that has a better explanation.

Thanks in advance !

5
  • 1
    In the Java 8 source code, the String(String) constructor reuses the value field from the parameter. Commented Jun 3, 2016 at 7:40
  • 2
    Just wondering: why would you care? One should avoid comparing strings with ==; so again ... what is the actual problem you intent to solve? Commented Jun 3, 2016 at 7:41
  • 1
    @AndyTurner I have an additional question - String stores a char[]-array internally. If the constructor String(String) is called, there is a reference to the char[]-array stored in the new string-instance. If I understand this the right way, s1 and s2 as described in the question are different instances, but internally the char[]-array would be the same on the heap. Or am I wrong with this? Commented Jun 3, 2016 at 8:14
  • 1
    @Supahupe that is exactly what I am saying in my answer below. Commented Jun 3, 2016 at 8:15
  • Thanks, I was not sure at first Commented Jun 3, 2016 at 8:16

2 Answers 2

2

In the Java 8 source code, the String(String) constructor reuses the value field from the parameter.

Note that value is a char[], though, so the two string instances use the same underlying array, but s2 is not using the "test" itself internally, since that is a String, not a char[].

Sign up to request clarification or add additional context in comments.

Comments

1

Here is the link to the Article by Corey McGlone

http://www.javaranch.com/journal/200409/Journal200409.jsp#a1

1 Comment

You should avoid Link-only answers because they are not useful if the link dies. Consider editing your answer to include the relevant details from the linked article.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.