Java深入理解null

来源:互联网 发布:传智播客java讲师 编辑:程序博客网 时间:2024/05/23 11:09

今天看《Java Puzzlers》的50道题目: Not your type

public static void main(String[] args) {String s = null;System.out.println(s instanceof String);}

输出是false,书中是这么解释的说instanceof的左操作数是null的话,则返回false, 另外instanceof的操作数必须是引用类型或者null,否则编译会报错。

另外如果instanceof的左右两个操作数如果都是类的话,其中一个必须是另一个的子类型,否则编译报错

public class Type2 {public static void main(String[] args) {//System.out.println(new Type2() instanceof String);  compile error}}


看了这个题目之后,我就在想null到底是个啥,以前还真没有深入的思考过这个问题,然后在JLS找到了null

首先在java中定义了三种类型:基本数据类型(primitive types),引用类型(reference types )以及特殊的null类型,null的官方描述如下:

There is also a special null type, the type of the expression null , which has no name.Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type.The null reference is the only possible value of an expression of null type.The null reference can always be assigned or cast to any reference type .In practice, the programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type.

 其中核心知识点如下(这个expression of null type不知道是啥):

1. null是没有名字的(不像基本数据类型int,float等),所以他不可能对变量设置空类型,并强制转换成null

2. null可以赋给任意的引用类型

然后null在内存中是怎样表示的呢?? JLS有这样一段描述

A reference value may also be the special null reference, a reference to no object, which will be denoted here by null. 
The null reference initially has no run-time type, but may be cast to any type. The default value of a reference type is null.

The Java Virtual Machine specification does not mandate a concrete value encoding null

最后一句说java虚拟机没有给定具体的编码给null, 但是我还是反编译一个文件看了瞎,发现虚拟机中用aconst_null来表示null object





0 0
原创粉丝点击