前言
对于Java开发者新手来说,空指针可真是老折磨大师了,甚至Java的发明者也承认这是一个巨大的设计错误。了解下面这些内容,可以有效的避免很多由null引起的错误。
null是任何引用类型的初始值
null 是所有引用类型的默认值,Java 中的任何引用变量都将nu作为默认值,也就是说所有 Object类下的引用类型默认值都是 null。这对所有的引用变量都适用。就像是基本类型的默认值一样,例如 int的默认值是 0,boolean 的默认值是 false。
null是一种特殊的值
null既不是对象也不是一种类型,它仅仅是一个特殊的值,可以将null转换为任何类型。在编译和运行期间,可以将null转为任何引用类型,并且不会抛出空指针异常。
public static void main(String[] args){
String str = null;
Integer itr = null;
Double dou = null;
Integer integer = (Integer)null;
String string = (String)null;
System.out.println("integer = " integer);
System.out.println("string = " string);
}
null 只能赋 值给引用变量,不能赋值给基本类型变量。
持有 null 的包装类在进行自动拆箱的时候,不能完成转换,会抛出空指针异常, null 也不能和基本数据类型进行对比
public static void main(String[] args) f
int i = 0:
Integer itr = null;
System.out.println(itr == 1) :
使用带有 null 值的引用类型变量,instanceof操作会返回 false
public static void main(String[] args){
Integer isNull = null;
// instanceof = isInstance 方法
if(isNul1 instanceof Integer) {
System.out.println("1sNull is instanceof Integer")
}else{
System. out.println("isNellis not instanceof integer");
}
}
这是instanceof 操作符一个很重要的特性,使得对类型强制转换检查很有用,静态变量为 null 调用静恋方法不会抛出 NulPointerException。因为静态方法使用了静态绑定。
注意大小写
null是Java中的关键字,也是大小写敏感的,不能写成Null或者NULL。但基本上不用担心写错,在编辑器中一般都会给出错误提示。
使用Null-Safe方法
应该使用 null-safe 安全的方法,java 类库中有很多工具类都提供了静态方法,例如基本数据类型的包装类, Integer Double 等。例如:
public class NullSafeMethod{
private static String number;
public static void main(String[] args){
Strings = String.value0f(number);
String string = number.toString();
System.out.println("s =" s):
System.out.println("string =" string)
}
}
number 没有赋值,所以默认为null,使用 String.value(number)静态方法没有拋出空指针异常,但是使用tostring()却抛出了空指针异常。所以尽量使用对象的静态方法。
null判断
你可以使用==或者!=操作来比较 null 值,但是不能使用某他算法或者逻辑操作,例如小于或大于。跟SQL不一样,在Java中 null==null 将返回 true,示例如下:
public class CompareNull{
private static String str1;
private static String str2;
public static void main(String[] args){
System.out.println("str1 == str2" srt1 == str2);
System.out.println(null == null);
}
}
本文出至:学新通技术网
标签: