While i was developing my Android application, my attention was caught by the backing array.
Multiple strings can share the same char[] because strings are immutable. The substring(int) method always returns a string that shares the backing array of its source string. Generally this is an optimization: fewer character arrays need to be allocated, and less copying is necessary. But this can also lead to unwanted heap retention. Taking a short substring of long string means that the long shared char[] won't be garbage until both strings are garbage. This typically happens when parsing small substrings out of a large input. To avoid this where necessary, call new String(longString.subString(...)). The string copy constructor always ensures that the backing array is no larger than necessary.
Then i have read many resources on the web. I know that Strings no longer shares the same backing array since jdk7u6, pointed by Mark Rotteveel.
Then i started trying to play with, and to test the existence of the shared backing array in my code:
String str = "1234567890";
System.out.println("str.substring(1): " + (str == str.substring(1)));
System.out.println("str.substring(0, 9): " + (str == str.substring(0, 9)));
First i assume == is a swallow equal comparison (isn't it?) that compares their memory locations (like what in C).
If they do share the same backing array, and == is just comparing their memory locations, both statements should return true (or at least the last one returns true).
However, they are both false.
Well, i think my laptop is having Java 7 update 21. (shown in Win7 -> Control Panel -> Java Control Panel -> About) (and also in Eclipse -> Window -> Preference -> Java -> Compiler -> Compiler compliance level: {1.3 , 1.4 , 1.5 , 1.6 , 1.7} )
And i know 1.7 means Java 7. And i know Java 7 is too high that the shared backing array may already have taken away. That is why i have asked Eclipse to compile my project with 1.5 and 1.6.
Java project -> Properties -> Java Complier -> Compiler compliance level = 1.5
However, as i said, i am still getting false in those println()s.
Let me summarise my questions:
Q1) How to use Java codes to verify there is a use of underlying backing array? (other than making the OutOfMemoryError by millions of substring()s)
Q1) a. Is == sallow equal comparison?
Q1) b. Am i really using Java 5/6 to compile, if i set Compiler compliance level = 1.5/1.6?
Thanks for any input :-)