本帖最后由 张洪慊 于 2015-11-5 18:38 编辑
String s1=new String("abc");//s1存放堆中对象引用(内存地址)
s2=new String("abc");//s2存放了另一个堆中对象引用(内存地址),有new就有对象(包括数组对象),在堆中分配新的内存单元
s2=new String("abc");
String s1="abc";
String s2="abc";//s1,s2引用都是常量池中的同一个常量"abc",即是说同一个引用
//以上所有的"abc"只有一份,在常量池中
测试代码:
package com.itheima;
public class StringTest {
public static void main(String[] args) {
String s1=new String("abc");//s1存放堆中对象引用(内存地址)
String s2=new String("abc");//s2存放了另一个堆中对象引用(内存地址),有new就有对象(包括数组对象),在堆中分配新的内存单元
System.out.println(s1==s2);
String s3="abc";
String s4="abc";//s1,s2引用都是常量池中的同一个常量"abc"
System.out.println(s3==s4);
}
}
反编译:javap -v com.itheima.StringTest:(一部分) ,-v只输出常量信息
Constant pool:
#1 = Class #2 // com/itheima/Java01
#2 = Utf8 com/itheima/Java01
#3 = Class #4 // java/lang/Object
#4 = Utf8 java/lang/Object
#5 = Utf8 <init>
#6 = Utf8 ()V
#7 = Utf8 Code
#8 = Methodref #3.#9 // java/lang/Object."<init>":()V
#9 = NameAndType #5:#6 // "<init>":()V
#10 = Utf8 LineNumberTable
#11 = Utf8 LocalVariableTable
#12 = Utf8 this
#13 = Utf8 Lcom/itheima/Java01;
#14 = Utf8 main
#15 = Utf8 ([Ljava/lang/String;)V
#16 = Utf8 Exceptions
#17 = Class #18 // java/io/UnsupportedEncodingException
#18 = Utf8 java/io/UnsupportedEncodingException
#19 = String #20 // abc
#20 = Utf8 abc
#21 = Fieldref #22.#24 // java/lang/System.out:Ljava/io/PrintStream;
#22 = Class #23 // java/lang/System
#23 = Utf8 java/lang/System
#24 = NameAndType #25:#26 // out:Ljava/io/PrintStream;
#25 = Utf8 out
#26 = Utf8 Ljava/io/PrintStream;
#27 = Methodref #28.#30 // java/io/PrintStream.println:(Z)V
#28 = Class #29 // java/io/PrintStream
#29 = Utf8 java/io/PrintStream
#30 = NameAndType #31:#32 // println:(Z)V
#31 = Utf8 println
#32 = Utf8 (Z)V
#33 = Utf8 args
#34 = Utf8 [Ljava/lang/String;
#35 = Utf8 str1
#36 = Utf8 Ljava/lang/String;
#37 = Utf8 str2
#38 = Utf8 StackMapTable
#39 = Class #34 // "[Ljava/lang/String;"
#40 = Class #41 // java/lang/String
#41 = Utf8 java/lang/String
#42 = Utf8 SourceFile
#43 = Utf8 Java01.java
简单解释下反编译结果:
Constant pool:即常量池
#1~#45代表常量池中有45个常量
你会发现只有一个abc
反编译这个东西暂时不要学,以后有兴趣在研究,我感觉非常难.参照 深入JVM相关书籍
|
|