public class HelloWorld{
public static void main(String []args){
String s="java";
s="world";
System.out.println(s);
}
}
Output:
world
public class HelloWorld{
public static void main(String []args){
String s="java";
s="world";
System.out.println(s);
}
}
Output:
world
You have two String
objects in that code: "java"
and "world"
. Each of them is immutable (unless you use reflection and rely on JDK internals). The s
variable first points to the first one, then to the second one, but they're separate objects.
After this:
String s="java";
you have something like this in memory:
+−−−−−−−−−−+ s:Ref3243−−−−−>| (string) | +−−−−−−−−−−+ +−−−−−−−−−+ | value: |−−−−−>| (array) | | ... | +−−−−−−−−−+ +−−−−−−−−−−+ | 0: 'j' | | 1: 'a' | | 2: 'v' | | 3: 'a' | +−−−−−−−−−+
Then after
s="world";
you have:
+−−−−−−−−−−+ | (string) | +−−−−−−−−−−+ +−−−−−−−−−+ | value: |−−−−−>| (array) | | ... | +−−−−−−−−−+ +−−−−−−−−−−+ | 0: 'j' | | 1: 'a' | | 2: 'v' | | 3: 'a' | +−−−−−−−−−+ +−−−−−−−−−−+ s:Ref6449−−−−−>| (string) | +−−−−−−−−−−+ +−−−−−−−−−+ | value: |−−−−−>| (array) | | ... | +−−−−−−−−−+ +−−−−−−−−−−+ | 0: 'w' | | 1: 'o' | | 2: 'r' | | 3: 'l' | | 4: 'd' | +−−−−−−−−−+
So the println
at the end shows the contents of the second string.
The value
member shown above may or may not be called value
in any given JDK implementation. It's a private data member.