什么是空?
null是任何东西的实例吗?
null属于哪个集合?
它在内存中是如何表示的?
什么是空?
null是任何东西的实例吗?
null属于哪个集合?
它在内存中是如何表示的?
当前回答
Null不是任何类的实例。
然而,你可以将null赋值给任何类型的变量(对象或数组):
// this is false
boolean nope = (null instanceof String);
// but you can still use it as a String
String x = null;
"abc".startsWith(null);
其他回答
An interesting way to see null in java in my opinion is to see it as something that DOES NOT denote an absence of information but simply as a literal value that can be assigned to a reference of any type. If you think about it if it denoted absence of information then for a1==a2 to be true doesn't make sense (in case they were both assigned a value of null) as they could really could be pointing to ANY object (we simply don't know what objects they should be pointing to)... By the way null == null returns true in java. If java e.g. would be like SQL:1999 then null==null would return unknown (a boolean value in SQL:1999 can take three values : true,false and unknown but in practise unknown is implemented as null in real systems)... http://en.wikipedia.org/wiki/SQL
字节码表示
Java的null有直接的JVM支持:使用三个指令来实现它:
aconst_null:例如,将一个变量设置为null,如Object o = null; Ifnull和ifnonnull:例如,if (o == null)将对象与null进行比较
第6章“Java虚拟机指令集”接着提到了null对其他指令的影响:它会对许多指令抛出NullPointerException异常。
2.4. “引用类型和值”在通用术语中也提到了null:
引用值也可以是特殊的空引用,即不指向任何对象的引用,这里用null表示。空引用最初没有运行时类型,但可以转换为任何类型。引用类型的默认值是null。
Java中的Null (tm)
在C和c++中,"NULL"是头文件中定义的常量,其值如下:
0
or:
0L
or:
((void*)0)
取决于编译器和内存模型选项。严格地说,NULL不是C/ c++本身的一部分。
在Java(tm)中,“null”不是关键字,而是null类型的特殊文字。它可以强制转换为任何引用类型,但不能转换为任何基本类型,如int或boolean。null字面量的值不一定是0。并且不可能强制转换为null类型或声明该类型的变量。
Null是一个特殊值,它不是任何类的实例。下面的程序说明了这一点:
public class X {
void f(Object o)
{
System.out.println(o instanceof String); // Output is "false"
}
public static void main(String[] args) {
new X().f(null);
}
}
Null是一个特殊值,它不是任何东西的实例。很明显,它不能是任何东西的实例。