1、程序题,当输入type=4时,写出以下代码的输出:
switch (type) {
default:
System.out.println(4);
case 1:
System.out.println(1);
case 2:
System.out.println(2);
case 3:
System.out.println(3);
}
答案:4
1
2
3
2、程序题,以下代码最后会抛出一个异常,是第几行抛出的:
try{
throw new Exception("1");
}catch (IOException e){
throw new Exception("2");
}catch (Exception e) {
throw new Exception("3");
}finally {
throw new Exception("4");
}
答案:(在main方法里测试)Exception in thread "main" java.lang.Exception: 4
3、程序题,以下代码哪一行编译出错?
public static void main(String[] args) {
short s1 = 1; //(赋值的时候没有超过short的最大范围,不会编译错误)
// 这一行代码会报编译错误
s1 = s1 + 1; //(type mismatch: cannot convert from int to short)
// 这一行代码没有报错
s1 = 1 + 1; //(赋值的时候没有超过short的最大范围,不会编译错误)
// 这一行代码也没有报错
s1 += 1; //(java语言规范中关于复合赋值的解释是这样的:E1 op=E2等价于 E1=(T)(E1 op E2),这里的T是E1的数据类型)
System.out.println(s1);
// 这一行代码会报编译错误
short s2=1;short s3=s1+s2;
/* 这两句代码也有编译错误,有些人会说了,难道同类型的数据还需要类型转换?答案是否定的,那么这里为什么会有编译错误呢,报错的原因主要是从数据安全方面考虑的,s1+s2的默认类型是int,因为如果s1的值接近short类型取值范围的最大值,同时s2的值也接近short类型取值范围的最大值,那么s1+s2的肯定超出了short的取值范围,此时二者之和就是int型的数据,此时就需要强制把左边的int型数据转换为右边的short型。有些人又说了,我明明写的s1为1,s2也为1,那为什么还报错,呵呵呵呵,因为此时还不知道s1和s2的值到底是多少,此处省去n个字。所以这两句代码正确的写法应该是short s1=1,s2=1;short s3=(short)(s1+s2); */
}