Java深入理解null

今天看《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





  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值