1

Where is the String value which is taken from user allocated in the memory?

Scanner input = new Scanner(System.in);
String x = "hello"; // This is stored in String constant pool
String y = "hello";
String z = new String("hello"); // This is stored in normal heap

System.out.println("Enter "+x);
String u = input.next(); // Where is this stored?

System.out.println(x==y) // true because same memory address in SCP
System.out.println(x==z) // false because one is stored in SCP and other in heap
System.out.println(u==x) // false then not in SCP
System.out.println(u==z) // false then not in heap either

is the value u stored in Stack then?

  • 2
    `System.out.println(u==z) // false then not in heap either` what makes you think so? It is still on the heap but not in the SCP. – Pshemo Jan 28 '20 at 18:48
  • Just because two objects are both stored in the heap doesn't make them the same object, which is what == is checking. – azurefrog Jan 28 '20 at 18:50
  • As @Pshemo says, two objects of the same type with the same contents can both be on the heap yet not both be the same object. – Jordan Jan 28 '20 at 18:50
  • 2
    What do you think should be result of `new String("hello") == new String("hello")` and why? – Pshemo Jan 28 '20 at 18:51
  • @Pshemo if the String value of u is in the heap the why did u==z return false? – Redwan Hossain Arnob Jan 28 '20 at 19:08
  • 1
    @RedwanHossainArnob It's not true that "the String value of u is in the heap". There is a String object in the heap that is pointed to by the variable `u`. That object has a value. There is a **different** String object in the heap that is pointed to by the variable `z`. It has the same value as the object identified by `u`, but they're _not the same object_. The equality operator (`==`) compares object **identity**, not object **contents**. This is why we use `.equals()` to compare objects when we care about their values being equal. – Jordan Jan 28 '20 at 19:12
  • 1
    @RedwanHossainArnob Let me ask counterquestion, why do you think it should return `true`? – Pshemo Jan 28 '20 at 19:15

2 Answers2

1

I looked into the Scanner class in OpenJdk8, and found that the string is stored within Scanner class as a CharBuffer.

public final class Scanner implements Iterator<String>, Closeable {

    // Internal buffer used to hold input
    private CharBuffer buf;
......
}
Arun
  • 3,333
  • 5
  • 31
  • 42
0

The confusion is due to the incorrect assumption (expressed in the comment on the last line of code) that if two strings are not maintained by the constant pool (that is, are "on the heap"), that they are the same object. They may actually be distinct objects:

String s1 = new String("test");
String s2 = new String("test");  // s1 != s2

The issue is not so much where a certain String object is allocated or not, but rather whether to strings are represented by the same object or not.

See also String Constant Pool

SDJ
  • 4,327
  • 1
  • 17
  • 33