edit when we want to use it like this String str1 = "Hello World";
we are using String Interning ( by the way its use it by many programming lanuage ) :
In computer science, string interning is a method of storing only one
copy of each distinct string value, which must be immutable. Interning
strings makes some string processing tasks more time- or
space-efficient at the cost of requiring more time when the string is
created or interned. The distinct values are stored in a string intern
pool.
JVM checks the String constant pool
first and if the string does not exist, it creates a new String object, how ? When the intern()
method is invoked on a String
object it looks the string contained by this String object in the pool, if the string is found there then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
example :
// s1 == s2 is false
String s1 = new String("sometext");
// s1 == s2 is true
//String s1 = new String("sometext").intern();
String s2 = s1.intern();
String s3 = "sometext";
System.out.println(s2 == s3);
another example (read abbas
value and change it)
String str = "abbas";
Field value = str.getClass().getDeclaredField("value");
value.setAccessible(true);
char[] Value = (char[]) value.get(str);
System.out.println("Value = " + Arrays.toString(Value));
char[] newVal = new char[]{'f','t','b','h','p'};
value.set(str,newVal);
Value = (char[]) value.get(str);
System.out.println("Value = " + Arrays.toString(Value));
//Value = [a, b, b, a, s]
//Value = [f, t, b, h, p]