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

1 Answers1

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,701
  • 5
  • 32
  • 43