Interview questions ((A) null) .fun () - Strong turn null value in java

Face questions Share

public class A {public static void fun1() {
        System.out.println("fun1");
    }

    public void fun2() {
        System.out.println("fun2");
    }

    public static void main(String[] args) {
        ((A) null).fun1();
        ((A) null).fun2();
    }
}
  • Title: The
    above code is to be compiled by?
    As can be, what is the result?

  • Answer: The
    code can be compiled by, null can be forced into any type, call the static method of its class is not an exception report, calling its class non-static method will be reported null pointer exception

understanding

执行下面代码打印结果为 null:
        A a = (A) null;
        System.out.println(a);

由于将 null 强转为 A 的对象,编译上可以通过,
但是实际值仍然为 null,非静态方法是属于对象的方法,
所以调用非静态方法会报空指针异常


执行以下代码不报异常:
        A a2 = null;
        a2.fun1();


由于 fun1 是静态方法,静态方法数随着类加载而加载的,
所以 java 编译器在编译的过程中对我们的代码进行的了优化,
我们通过查看 class 文件即可看出,这两行代码改变成为了下面的样式:

        A a2 = null;
        fun1();

the reason

java compiler is optimized for use in the class object to call a static method. For a2.fun1 () to optimized fun1 ()

java is recommended to use the class name directly call the static method , thereby reducing the work of the compiler to improve the coding efficiency.

As shown: the left java source file, the right to compile the class file

1.jpg

Guess you like

Origin www.cnblogs.com/upuptop/p/11229146.html