你是不是说String.intern()方法: Returns a canonical representation for the string object. A pool of strings, initially empty, is maintained privately by the class String. When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true. 这个是由java虚拟机实现的
String s1 = "abc";
如果在此之前,没有出现过"abc",那就在常量池建一个"abc"对象.
然后把s1直接指向常量池中该对象的位置.
String s2 = new String("abc");
s2指向堆内存中的一个String类对象,该对象中有个引用指向常量池中的"abc";
还有问题请问:我也认为常量池应该是不接受赋值操作,可是jvm规范中说一个类型中的直接常量(string,integer,float point常量)放在常量池中,怎么理解?
Returns a canonical representation for the string object.
A pool of strings, initially empty, is maintained privately by the class String. When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true. 这个是由java虚拟机实现的
在java文件编译成class文件字节码时,并不知道class文件被加载到内存的实际地址,因此采用符号引用。比如org.simple.People引用了org.simple.Tool类,但在编译时,并不知道Tool类在内存中的实际地址,因此将使用符号org.simple.Tool(假设)来代替,而在这些类被载入后,People类将能获取到Tool类的内存地址(通过虚拟机),因此此时就可以将符号org.simple.Tool替换为Tool类的实际内存地址了,即直接引用地址。