Java中null关键字

来源:互联网 发布:淘宝新店怎样开直通车 编辑:程序博客网 时间:2024/06/10 07:36

本文系转载,原文链接:http://www.importnew.com/14229.html

1.首先,null是Java中的关键字,像public,static,final。它是大小写敏感的,不可以写成NUll或者Null,编译器将不能识别然后报错。

2.每一种原始类型都有默认值,如int默认值是0,boolean的默认值为false,null是任何引用类型的默认值,不严格的说是所有object类型的默认值。这对所有变量都是适用的。如成员变量、局部变量、实例变量、静态变量(当使用一个没有初始化的局部变量,编译器会发出警告)。比如:

private static Object myObj;public static void main(String args[]){    System.out.println("What is value of myObjc : " + myObj);}//结果What is value of myObjc : null

3.null既不是对象也不是一种类型,它仅是一种特殊的值,你可以将其赋予任何引用类型,你也可以将null转化成任何类型,如下面的代码:

String str = null; // null can be assigned to StringInteger itr = null; // you can assign null to Integer alsoDouble dbl = null;  // null can also be assigned to DoubleString myStr = (String) null; // null can be type cast to StringInteger myItr = (Integer) null; // it can also be type casted to IntegerDouble myDbl = (Double) null; // yes it's possible, no error

可以看到在编译和运行时期,将null强制转换成任何引用类型都可行,在运行时期都不会抛出空指针异常。

4.null可以赋值个引用变量,但你不能将它赋值给基本类型变量,否则,编译器将会报错,如下所示

int i = null; // type mismatch : cannot convert from null to intshort s = null; //  type mismatch : cannot convert from null to shortbyte b = null: // type mismatch : cannot convert from null to bytedouble d = null; //type mismatch : cannot convert from null to doubleInteger itr = null; // this is okint j = itr; // this is also ok, but NullPointerException at runtime

当你直接将null赋值给基本类型,会出现编译错误,但是如果将null赋值给包装类object,然后将object赋给各自的基本类型,编译不会报错,但会在运行时期遇到空指针异常。这是Java的自动拆箱造成的。

5.任何含有null值的包装类在Java拆箱生成基本数据类型时候都会抛出一个空指针异常。有些人会犯这样的错误,他们认为自动装箱会将null转换成各自基本类型的默认值,例如对于int转换成0,布尔类型转换成false,但是那是不正确的,如下所示:

Integer iAmNull = null;int i = iAmNull; // Remember - No Compilation Error

当运行上面的代码片段的时候,会在控制台看到主线程抛出空指针异常。在使用HashMap和Integer键值的时候会发生很多这样的错误。当你运行下面代码的时候就会出现错误。

import java.util.HashMap;import java.util.Map;/** * An example of Autoboxing and NullPointerExcpetion *  * @author WINDOWS 8 */public class Test {    public static void main(String args[]) throws InterruptedException {      Map numberAndCount = new HashMap<>();      int[] numbers = {3, 5, 7,9, 11, 13, 17, 19, 2, 3, 5, 33, 12, 5};      for(int i : numbers){         int count = numberAndCount.get(i);         numberAndCount.put(i, count++); // NullPointerException here      }           }}

输出:

Exception in thread "main" java.lang.NullPointerException at Test.main(Test.java:25)

这段代码看起来非常简单并且没有错误。你所做的一切是找到一个数字在数组中出现了多少次,这是Java数组中典型的寻找重复的技术。开发者首先得到以前的数值,然后再加一,最后把值放回Map里。程序员可能会以为,调用put方法时,自动装箱会自己处理好将int装箱成Integer,但是他们忘记了当一个数字没有计数值的时候,HashMap的get()方法将返回null。而不是0,因为Integer的默认值是null而不是0.当把null传递给一个int型变量的时候自动装箱将会返回空指针异常。

6.如果使用了带有null值的引用类型变量,instanceof操作将会返回false:

Integer iAmNull = null;if(iAmNull instanceof Integer){   System.out.println("iAmNull is instance of Integer");                             }else{   System.out.println("iAmNull is NOT an instance of Integer");}

输出:

iAmNull is NOT an instance of Integer

7.你可能知道不能调用非静态方法来使用一个值为null的引用类型变量。它将会抛出空指针异常,但是你可能不知道,你可以使用静态方法来使用一个值为null的引用类型变量。因为静态方法使用静态绑定,不会抛出空指针异常。下面是一个例子:

public class Testing {                public static void main(String args[]){      Testing myObject = null;      myObject.iAmStaticMethod();      myObject.iAmNonStaticMethod();                                }   private static void iAmStaticMethod(){        System.out.println("I am static method, can be called by null reference");   }   private void iAmNonStaticMethod(){       System.out.println("I am NON static method, don't date to call me by null");   }

输出:

I am static method, can be called by null referenceException in thread "main" java.lang.NullPointerException               at Testing.main(Testing.java:11)

8.你可以将null传递给方法使用,这是方法可以接受任何引用类型,例如public void print(Object obj)可以这样调用print(null)。从编译角度看这是可以的,但结果完全取决于方法。null安全的方法,如在这和例子中的print方法,不会抛出空指针异常,只是优雅的退出。如果业务逻辑允许的话,推荐使用null安全的方法。

9.你可以使用==或者!=操作来比较null值,但是不能使用其他算法或者逻辑操作,例如小于或者大于。跟SQL不一样,在Java中null==null将返回true,如下所示:

public class Test {    public static void main(String args[]) throws InterruptedException {       String abc = null;       String cde = null;       if(abc == cde){           System.out.println("null == null is true in Java");       }       if(null != null){           System.out.println("null != null is false in Java");        }       // classical null check       if(abc == null){           // do something       }       // not ok, compile time error       if(abc > null){       }    }}

输出:

null == null is true in Java

记住,null是任何一个引用类型变量的默认值,在Java中你不能使用null引用来调用任何instance方法或者instance变量。

0 0
原创粉丝点击