Java中的null到底是什么(◎_◎;)
一、null是个啥?
JLS 4.1 The Kinds of Types and Values
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. Thenull
reference is the only possible value of an expression of null type. Thenull
reference can always be cast to any reference type. In practice, the programmer can ignore the null type and just pretend thatnull
is merely a special literal that can be of any reference type.
//false
System.out.println(null instanceof Object);
一种特殊的类型(姑且称之为null类型吧~),没有名称无法声明null类型的变量或转换为null类型,空引用是null类型表达式的唯一可能值, nullreference总是可以强制转换为任何引用类型
二、null在内存中是怎么样的存在?
What exactly is null in memory? Or What is the null value in Java?
First of all, null is not a valid object instance, so there is no memory allocated for it. It is simply a value that indicates that the object reference is not currently referring to an object.
From JVM Specifications:
The Java Virtual Machine specification does not mandate a concrete value encoding null.
Java虚拟机规范没有强制要求编码null的具体值
三、null的使用
- Uninitialized state
- Termination condition
- Non-existing object
- An unknown value
1、null是任何引用类型的默认值
public class Test {
private static String str;
public static void main(String args[]) {
System.out.println(str); //null
}
}
2、null可以赋给引用类型,不能赋给基本类型,可以将null转化为任何引用类型
Integer num1 = null;
int num3 = null; //编译器报错
Integer num2 = (Integer)null;
String str = (String)null;
Test test = (Test)null;
3、null值的引用类型变量可以调用静态方法、静态变量,不能调用实例方法、实例变量
public class Test {
public static String name="Qpee";
public int age=18;
public static void main(String args[]) {
Test test1 = null;
Test test2 = (Test)null;
System.out.println(test1.name); //Qpee
System.out.println(test1.age); //Exception in thread "main" java.lang.NullPointerException
System.out.println(test2.name); //Qpee
System.out.println(test2.age); //Exception in thread "main" java.lang.NullPointerException
test1.print1(); //Exception in thread "main" java.lang.NullPointerException
test1.print2(); //static method
test2.print1(); //Exception in thread "main" java.lang.NullPointerException
test2.print2(); //static method
}
public void print1(){
System.out.println("instance method");
}
public static void print2(){
System.out.println("static method");
}
}
四、Other
1、我丢一个null~~
public class Test {
public static void main(String args[]) {
try{
throw null;
}catch (Exception ex){
System.out.println(ex instanceof Object); //true
System.out.println(ex.getClass().getName()); //java.lang.NullPointerException
}
}
}
If evaluation of the Expression completes normally, producing a null value, then an instance V' of class NullPointerException is created and thrown instead of null.
如果表达式产生一个空值,则创建类NullPointerException的实例并抛出
五、Reference
What exactly is null in Java ?
Why can I throw null in Java ?