分享

java易错笔试题

 心本心123 2022-08-21 发布于广东

1.

int[] arr = new int[10]; System.out.println(arr);//地址值?

char[] arr1 = new char[10]; System.out.println(arr1); //地址值?

测试:

public class ArrayPrintTest {

public static void main(String[] args) {

int[] arr = new int[]{1,2,3};

System.out.println(arr);//地址值

char[] arr1 = new char[]{'a','b','c'};

System.out.println(arr1); //abc

}

}

原因:

8db5a0d42d7f181fcbd8e0e366487eef.png

2.

//面试题:多态是编译时行为还是运行时行为?

//证明如下:

class Animal  {

protected void eat() {

System.out.println('animal eat food');

}

}

class Cat  extends Animal  {

protected void eat() {

System.out.println('cat eat fish');

}

}

class Dog  extends Animal  {

public void eat() {

System.out.println('Dog eat bone');

}

}

class Sheep  extends Animal  {

public void eat() {

System.out.println('Sheep eat grass');

}

}

public class InterviewTest {

public static Animal  getInstance(int key) {

switch (key) {

case 0:

return new Cat ();

case 1:

return new Dog ();

default:

return new Sheep ();

}

}

public static void main(String[] args) {

int key = new Random().nextInt(3);

System.out.println(key);

Animal  animal = getInstance(key);

animal.eat();

}

}

3.

//考查多态的笔试题目:

public class InterviewTest1 {

public static void main(String[] args) {

Base1 base = new Sub1();

base.add(1, 2, 3);

Sub1 s = (Sub1)base;

s.add(1,2,3);

}

}

class Base1 {

public void add(int a, int... arr) {

System.out.println('base1');

}

}

class Sub1 extends Base1 {

public void add(int a, int[] arr) {

System.out.println('sub_1');             //容易混淆

}

public void add(int a, int b, int c) {

System.out.println('sub_2');

}

}

答案:

e25a4732eefe66c6e037c40b552939f9.png

4.

/*

* 关于包装类使用的面试题

*

*

*/

public class InterviewTest {

@Test

public void test1() {

Object o1 = true ? new Integer(1) : new Double(2.0);       三元运算符 A 和 B 类型能统一成一个类型。这边就类型提升为double

System.out.println(o1);// 1.0

}

@Test

public void test2() {

Object o2;

if (true)

o2 = new Integer(1);

else

o2 = new Double(2.0);

System.out.println(o2);// 1

}

@Test

public void test3() {

Integer i = new Integer(1);

Integer j = new Integer(1);

System.out.println(i == j);//false    不是同一个对象

//Integer内部定义了IntegerCache结构,IntegerCache中定义了Integer[],

//保存了从-128~127范围的整数。如果我们使用自动装箱的方式,给Integer赋值的范围在

//-128~127范围内时,可以直接使用数组中的元素,不用再去new了。目的:提高效率

Integer m = 1;

Integer n = 1;

System.out.println(m == n);//true

Integer x = 128;//相当于new了一个Integer对象

Integer y = 128;//相当于new了一个Integer对象

System.out.println(x == y);//false

}

}

5.接口

class C extends B implements A {

System.out.println(x);  编译不通过。因为x是不明确的

System.out.println(super.x);   // 1    (调用父类B中的变量x,可以通过super.x调用)

System.out.println(A.x);   // 0     (调用A类的变量x,此时的A类的变量x是全局常量可以直接通过类.属性调用 )

}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多