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 !

sumit
  • 3,210
  • 1
  • 19
  • 37
  • 1
    In [the Java 8 source code](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/lang/String.java/#151), the `String(String)` constructor reuses the `value` field from the parameter. – Andy Turner Jun 03 '16 at 07: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? – GhostCat Jun 03 '16 at 07: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? – Supahupe Jun 03 '16 at 08:14
  • 1
    @Supahupe that is exactly what I am saying in my answer below. – Andy Turner Jun 03 '16 at 08:15
  • Thanks, I was not sure at first – Supahupe Jun 03 '16 at 08:16

2 Answers2

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[].

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
1

Here is the link to the Article by Corey McGlone

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

  • 1
    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. – Andy Turner Jun 03 '16 at 08:39