1、代码运行步骤
- 首先,虚拟机进程首先从classpath中找到Text.class文件,读取这个文件中的二进制数据,然后吧Text类的信息存放到运行时数据区的方法区中。
- 然后,JVM定位到方法区中的Text类的Main方法的字节码,开始执行它的指令。
- 在堆内为一个新的实例分配内存,这个实例持有着
2、类的加载顺序
-
父类静态代码块(不包括静态方法);
-
子类静态代码块(不包括静态方法);
-
父类非静态代码块;
-
父类构造函数;
-
子类非静态代码块;
-
子类构造函数。
其中前两个不需要new类实例的时候就执行了,在类加载到方法区的时候就开始执行了。 -
Base b = new Sub();编译为Base类,运行为Sub类/
3、String
String a="AA";
String b="AA";
String c=new String("AA");
- a、b和堆中创建的AA都是指向JVM字符串常量池中的"AA"对象,他们指向同一个对象。new关键字一定会产生一个对象AA,同时这个对象是存储在堆中。所以String c=new String(“AA”)这一句应该产生了两个对象:保存在方法区中字符串常量池的AA和保存堆中AA。c—>堆AA—>池AA。A—>池AA—>堆AA。
- 使用“”创建的字符串都是常量,编译器就已经确定存储到String Pool中;
- 使用new创建的对象存储到heap中,运行期新创建的;
- 使用“aa” + "aa"也是常量;
- “aa” + s1是运行期才创建的,存储到heap中;
- 若用final修饰,则s1属于常量,存储到String Pool中。
String str3 = new String("aaa");
String str4 = new String("aaa");
System.out.println(str3 == str4);// false 可以看出用new的方式是生成不同的对象,比较堆上的
String s0="helloworld";
String s1="helloworld";
String s2="hello"+"world";
System.out.println(s0==s1); //true 可以看出s0跟s1是指向同一个对象
System.out.println(s0==s2); //true 可以看出s0跟s2是指向同一个对象
String st0="helloworld";
String st1=new String("helloworld");
String st2="hello" + new String("world");
System.out.println( st0==st1 ); //false 用new String() 创建的字符串不是常量,不能在编译期就确定
System.out.println( st0==st2 ); //false st2地址存在堆中,不可能相同
System.out.println( st1==st2 ); //false
String stri1="abc";
String stri2="def";
String stri3=stri1+stri2;
System.out.println(stri3=="abcdef"); //false 变量相+是在的堆内存中创建
String strin0 = "a1";
String strin1 = "a" + 1; //这种不是变量,是常量
System.out.println((strin0 == strin1)); //result = true
String ss0 = "ab";
final String ss1 = "b";
String ss2 = "a" + ss1;
System.out.println((ss0 == ss2)); //result = true 对于final修饰的变量,它在编译时被解析为常量值的一个本地拷贝存储到自己的常量池中或嵌入到它的字节码流中。所以此时的"a" + s1和"a" + "b"效果是一样的