please see the following code.
String s = 'Monday'; if(s.subString(0,3).equals('Mon'){} String s2 = new String(s.subString(0,3)); String s3 = s.subString(0,3);
I know that line 2 will still point to ‘Monday’ and have a new String object with the offset and count set to 0,3.
The line 4 will create a new String ‘Mon’ in string pool and point to it.
But not sure what about line 5 whether it will behave like line 2 or line 4.
If i am wrong for line 2 or 4 also please correct..
That is currently true of the Sun JRE implementation. I seem to recall that was not true of the Sun implementation in the past, and is not true of other implementations of the JVM. Do not rely on behaviour which is not specified. GNU classpath might copy the array (I can’t remember off hand what ratio is uses to decide when to copy, but it does copy if the copy is a small enough fraction of the original, which turned one nice O(N) algorithm to O(N^2)).
No, it creates a new string object in the heap, subject to the same garbage collection rules as any other object. Whether or not it shares the same underlying character array is implementation dependant. Do not rely on behaviour which is not specified.
The
String(String)constructor says:The
String(char[])constructor says:Following good OO principles, no method of
Stringactually requires that it is implemented using a character array, so no part of the specification ofStringrequires operations on an character array. Those operations which take an array as input specify that the contents of the array are copied to whatever internal storage is used in the String. A string could use UTF-8 or LZ compression internally and conform to the API.However, if your JVM doesn’t make the small-ratio sub-string optimisation, then there’s a chance that it does copy only the relevant portion when you use
new String(String), so it’s a case of trying it a seeing if it improves the memory use. Not everything which effects Java runtimes is defined by Java.To obtain a string in the string pool which is
equalto a string, use theintern()method. This will either retrieve a string from the pool if one with the value already has been interned, or create a new string and put it in the pool. Note that pooled strings have different (again implementation dependent) garbage collection behaviour.