Java的执行顺序,笔试遇到的问答题(做完这题执行顺序不会再错)
2013-09-24 00:01
232 查看
public class Test { public static int k = 0; public static Test t1 = new Test("t1"); public static Test t2 = new Test("t2"); public static int i= print("i"); public static int n = 99; { print("构造块"); } static{ print("静态块"); } public Test(String str) { System.err.println(++k + ":" + str + " i=" + i + " n=" + n); ++n; } public static int print(String str) { System.err.println(++k + ":" + str + " i=" + i + " n=" + n); ++n; return ++i; } public static void main(String[] args) { Test test = new Test("init"); System.out.println("========================================="); Test test1 = new Test("init1"); } }
经过查看课本和Debug追踪:
1.当第一次创建类时,会给这个类的成员变量中静态变量 给予初始值(int为0,boolean为false)
2. 根据代码 给静态变量赋值
3. 静态块
4.初始化成员变量中的非静态变量
5. 构造块
第二次创建时:
由上述的 4. 开始执行。
特殊情况:
静态变量中 又是创建这个类??
答:经过debug追踪,发现这个类时直接上述的 4. 开始执行。
debug模式下结果:(注意如果直接执行 :是优化过的,结果就不同)
1: j i=0 n=0
2: 构造块 i=1 n=1
3: t1 i=2 n=2
4: j i=2 n=3
5: 构造块 i=3 n=4
6: t2 i=4 n=5
7: i i=4 n=6
8: 静态块 i=5 n=99
9: j i=6 n=100
10: 构造块 i=7 n=101
11: init i=8 n=102
=========================================
12: j i=8 n=103
13: 构造块 i=9 n=104
14: init1 i=10 n=105
相关文章推荐
- 由阿里巴巴一道笔试题看Java静态代码块、静态函数、动态代码块、构造函数等的执行顺序
- 一道Java笔试题:静态语句块、构造语句块和构造函数的执行顺序
- 由阿里巴巴一道笔试题看Java静态代码块、静态函数、动态代码块、构造函数等的执行顺序
- 【一道航天信息java笔试题】return语句和finally语句的执行顺序
- Java面试中经常遇到的类执行顺序
- 由阿里巴巴一道笔试题看Java静态代码块、静态函数、动态代码块、构造函数等的执行顺序
- 一道Java笔试题:静态语句块、构造语句块和构造函数的执行顺序
- java利用CountDownLatch来制定线程执行顺序
- JAVA程序执行顺序
- java程序中方法执行的前后顺序
- 通过指令码来判断Java代码的执行顺序(++问题与return和finally的问题)
- java 中执行顺序
- java中子类继承父类程序执行顺序问题
- 转来的:java中静态块和构造函数的执行顺序问题
- (转)java for循环的执行顺序和几种常用写法
- 深入了解Java程序执行顺序
- 08-02 Java 代码块,代码块执行的先后顺序问题
- Java 静态语句块、语句块、构造函数执行顺序
- Java异常----try、catch和finally块中的return执行顺序
- java代码块执行顺序