能看懂的人不用我解释,看不懂的人自己代码敲一遍才有印象,直接上代码:
1. e.printStackTrace(); 能输出“break 1”吗?
try {
throw new RuntimeException();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("break 1");
答:会。
2.throw new RuntimeException(); 下面代码块输出结果是什么?
//代码块1
throw new RuntimeException();
System.out.println("break 1");
//代码块2
Integer a =null;
int b=a;
System.out.println("break 2");
答:代码块1 编译不过。 代码块2抛错,不会输出结果。
3. 自递增i++ 和++i 。下面各个代码块输出结果是什么?
//代码块1
int num = 0;
System.out.println(num++);
//代码块2
int num = 0;
System.out.println(++num);
//代码块3
int num = 0;
System.out.println(num++);
System.out.println(++num);
//代码块4
int num = 0;
System.out.println(++num);
System.out.println(num++);
答:代码块1输出:0 ;代码块2输出:1 ; 代码块3:0 和2 ; 代码块4输出:1 和 1
4.try..catch..finally{} 。 下面程序输出结果是?
public class Test {
public static int test() {
int num = 0;
try {
return num++;
} catch (Exception e) {
e.printStackTrace();
}finally{
return ++num;
}
}
public static void main(String[] args) {
System.out.println(test());
}
}
答:2
5. switch..case 没接break易错点。下面代码输出什么?
public static void main(String[] args) {
int i = 1;
switch (i) {
case 0:
System.out.println(0);
case 1:
System.out.println(1);
case 2:
System.out.println(2);
break;
default:
System.out.println(3);
}
}
答:输出1 和 2
6.封装类型Integer判断相等。下面各个代码块输出结果是?
// 代码块1
Integer a = 127;
Integer b = 127;
System.out.println(a == b);
// 代码块2
Integer c = 128;
Integer d = 128;
System.out.println(c == d);
System.out.println(c.equals(d));
// 代码块3
int e = 128;
Integer f = 128;
System.out.println(e == f);
// 代码块4
Integer g = 128;
System.out.println(128 == g);
答:依次输出 1-true ;2-false true ; 3-true;4-true
7. 接着第4点的内容出个题,看看你结果如何?重点看代码2
//代码1 能编译通过吗?为什么?
public class Test {
public static int test(){
try {
return 0;
} catch (Exception e) {
}finally{
return 1;
}
return 2;
}
public static void main(String[] args) {
System.out.println(test());
}
}
//代码2 输出结果是什么?为什么?(易错)做多了finally的人这题容易错。
public class Test {
public static int test(){
try {
return 0;
} catch (Exception e) {
}finally{
//return 1;
}
return 2;
}
public static void main(String[] args) {
System.out.println(test());
}
}
//代码3 输出结果是什么?为什么?
public class Test {
public static int test(){
try {
return 0;
} catch (Exception e) {
}finally{
return 1;
}
//return 2;
}
public static void main(String[] args) {
System.out.println(test());
}
}