java面试题

      下面的代码有什么不妥之处?

1. if(username.equals(“wpc”)){}

2. int x = 1;

return x==1?true:false;

回答一问题:如果username初值为null在编译的时候会有警告,运行的时候抛出异常

如果username写在后面即使初值为null也不会抛异常

回答问题二:代码冗余无需还要三木运算符判断是否为true或者false,直接返回boolean类型就可以了

也就是说wpc.equals(username)更好;return x= =1,就可以了。

----------------------------------时间分割线-------------------------------------------

1.public static void main(String[] args) {
        // TODO 自动生成的方法存根
        Thread t = new Thread() {
            public void run() {
                pong();
            }
        };
 
        t.start();
        System.out.print("ping");
 
    }
  static void pong() {
    System.out.print("pong");
     
    }
 
}

会输出什么?答案是:pongping和pingpong都有可能。

public static void main(String[] args) {
        // TODO 自动生成的方法存根
        Thread t = new Thread() {
            public void run() {
                pong();
            }
        };
 
        t.run();
        System.out.print("ping");
 
    }
  static void pong() {
    System.out.print("pong");
     
    }
 
}

会输出什么?答案是:pongping。

解析:由于启动多线程的方法是start()而非run(),所以第二个代码片段,根本不是多线程,只有一个主线程在运行,调用了重写的run()而已;第一个代码段中,主线程和子线程是随机执行的,谁能抢到CPU的资源,谁就执行。

2.

public void getCustomerInfo() {


        try {


            // do something that may cause an Exception


        } catch (java.io.FileNotFoundException ex) {


            System.out.print("FileNotFoundException!");


        } catch (java.io.IOException ex) {


            System.out.print("IOException!");


        } catch (java.lang.Exception ex) {


            System.out.print("Exception!");


        }


    }
A IOException!


BIOException!Exception!


CFileNotFoundException!IOException!


DFileNotFoundException!IOException!Exception!


答案:A

解析:只catch一次,能匹配到就终止,不再抛错误。

3.

新建一个流对象,下面哪个选项的代码是错误的?()

A)new BufferedWriter(new FileWriter("a.txt"));

B)new BufferedReader(new FileInputStream("a.dat"));

C)new GZIPOutputStream(new FileOutputStream("a.zip"));

D)new ObjectInputStream(new FileInputStream("a.dat"));

答案:B

JAVA的IO继承树


4.



下列哪种异常是检查型异常,需要在编写程序时声明?
  • A.NullPointerException
  • B.ClassCastException
  • C.FileNotFoundException
  • D.IndexOutOfBoundsException
  • 答案为C

绿色部分Exception是非检查型异常,必须run一下才会发现。其他的在编译时就会发现。

5.序列化问题。

JAVA种带有transient和static关键字的变量,不会被序列化。static变量和类同级别,序列化针对的是对象。

6.hashmap、arraylist原理以及扩容问题,另开一个博文说明。

7.JAVA构造函数加载顺序。牵扯到JAVA加载顺序,另开一个博文说明。

8.static变量会被初始化为0,字符串是null。局部变量不初始化编译不通过。

9.接口和抽象类的区别与联系,以及其中的变量、函数的类型,另开博文说明。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值