1.举例子:
在主方法中调用m1方法,finally中 i 变量自增,但结果却是10
public static void main(String[] args) { int i = m1(); System.out.println(i);// 10 } public static int m1() { int i = 10; try { return i; } finally { i++; System.out.println("m1的i=" + i);// 11 } }
2.解释原因:
public static int m1() { int i = 10; try { int temp = i; return temp; } finally { i++; System.out.println("m1的i=" + i);// 11 } }
其实将i赋给了临时变量temp return返回的是temp,而不是变量 i .
===========================================================
finally是一定会执行的,一般在finally语句块中释放资源,比如io的关闭等等