Will two same strings read from the System.in be stored in a common memory location?

java

Solution

The pool is implemented as a hashed data structure. Java leaves the decision about whether to do the search, and share non-literal String objects, up to the programmer. See the String method intern().

Problem

Suppose we have program like this: ``` import java.io.*; public class ReadString { public static void main (String[] args) { // prompt the user to enter their name System.out.print("Enter your name: "); // open up standard input BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String userName = null; String userNameCopy = null; // read the username from the command-line; need to use try/catch with the // readLine() method try { userName = br.readLine(); System.out.print("Enter your name once again: "); userNameCopy = br.readLine(); } catch (IOException ioe) { System.out.println("IO error trying to read your name!"); System.exit(1); } System.out.println("Thanks for the name, " + userName); } } // end of ReadString class ``` Now, if user types his username twice, `userName` and `userNameCopy` Strings will have the same value. Since strings are immutable, will Java compiler be smart enough to use only one memory object with the two references to it, or is this behavior reserved only for the string literals hard-coded into the program? If the answer is "No, compiler will create two separate object on the heap". why is that so? Is it because searching for the exact match from the pool is slow? If it is, couldn't string pool be implemented like some sort of hash table, or something similar?

Original source

Related problems