0
点赞
收藏
分享

微信扫一扫

笔试题考的是你的基础牢不牢靠



笔试题考的是你的基础牢不牢靠_成员变量

请看题:


public class IntegerDemo {	
    public static void main(String[] args) {	
        IntegerDemo integerDemo = new IntegerDemo();	
        integerDemo.test();	
        int j = integerDemo.test();	
        System.out.println(j);	
    }	
    private int test() {	
      static int i = 0;	
        i++;	
        return i;	
    }	
}


上面这道题目输出什么?


A:0  B:1  C:2  D:编译失败。


先自己琢磨一下,答案是什么。

本题考查的是大家对Java语言中的static静态知识的掌握情况。在Java语言中,方法名称、成员变量都可以使用关键字static来修饰,但是局部变量是不能使用static来修饰的,同时因为方法体内的变量是局部变量,所以上面的代码中test方法内的 i变量是不能用static来修饰的,从而导致编译时通不过的,正确的做法是把static去掉或者把i转为成员变量。

所以上面题目的答案:D。

调整代码,去掉上题中局部变量static的修饰:


public class IntegerDemo {	
    public static void main(String[] args) {	
        IntegerDemo integerDemo = new IntegerDemo();	
        integerDemo.test();	
        int j = integerDemo.test();	
        System.out.println(j);	
    }	
    private int test() {	
        int i = 0;//局部变量	
        i++;	
        return i;	
    }	
}


笔试题考的是你的基础牢不牢靠_局部变量_02

运行结果:1

调整代码中的局部变量为成员变量:


public class IntegerDemo {	
    static int i = 0;//成员变量	
    public static void main(String[] args) {	
        IntegerDemo integerDemo = new IntegerDemo();	
        integerDemo.test();	
        int j = integerDemo.test();	
        System.out.println(j);	
    }	
    private  int test() {	
        i++;	
        return i;	
    }	
}


输出结果:2

不要小看每个笔试题,每个笔试题目其实都在考察你的Java基础知识掌握的情况是否牢靠。


举报

相关推荐

0 条评论