I want to check how immutable string variables store only one address location.
For example,
String s1="welcome"
String s2="welcome"
then s1 and s2 reference the same one string "welcome" store address.
I want to check how immutable string variables store only one address location.
For example,
String s1="welcome"
String s2="welcome"
then s1 and s2 reference the same one string "welcome" store address.
String pool is a memory area of Heap where all the Strings are located by the java virtual machine.
In the String pool there is an another small portion of memory to store String constants or literals. So, String constant pool is subset of String pool in the Heap space.
Consider following example,
String cPoolStr1 = "Hello";
String cPoolStr2 = "Hello";
String sPoolStr1 = new String("Hello");
String sPoolStr2 = new String("Hello");
To check whether both are referring to the same address you will get true
for cPoolStr1 == cPoolStr2
which compares the reference of the literals.
String literals are stored in a common pool. Typically a part of heap.
Secondly, no you can't get address of an Object in Java. It changes over time with GC.
However you can check the hashcode of two objects to see weather they are sharing the same address at given point of time.
System.out.println(s1.hashCode()+" ** " +s2.hashCode());
Where hashcode()
method
(This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)
Give a shot on the answer :How can a string be initialized using " "?