假设我们有这样的程序:
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
现在,如果用户输入他的用户名两次,userName
字符串userNameCopy
将具有相同的值。由于字符串是不可变的,Java 编译器是否足够聪明,可以只使用一个内存对象和两个对它的引用,还是这种行为只保留给硬编码到程序中的字符串文字?
如果答案是“否,编译器将在堆上创建两个单独的对象”。为什么呢?是因为从池中搜索完全匹配的速度很慢吗?如果是这样,字符串池不能像某种哈希表或类似的东西那样实现吗?