-1

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.

Pang
  • 9,564
  • 146
  • 81
  • 122
  • 1
    The compiler puts `"welcome"` in the string pool of the class file and lets both `s1` and `s2` point to the same string. – aioobe Aug 23 '15 at 06:42
  • 2
    possible duplicate of [What is the Java string pool and how is "s" different from new String("s")?](http://stackoverflow.com/questions/2486191/what-is-the-java-string-pool-and-how-is-s-different-from-new-strings) – mlt Aug 23 '15 at 07:00

2 Answers2

2

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.

enter image description here

akash
  • 22,664
  • 11
  • 59
  • 87
0

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 " "?

Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307