Java之null保留字

概要

null既不是对象,也不是一种类型

a.它是一种特殊的值,你可以将其赋予任何引用类型。
b.在编译和运行时期,将null强制转换成任何引用类型都是可行的,在运行时期都不会抛出空指针异常。
String str = null; // null can be assigned to String
Integer itr = null; // you can assign null to Integer also
Double dbl = null; // null can also be assigned to Double

String myStr = (String) null; // null can be type cast to String
Integer myItr = (Integer) null; // it can also be type casted to Integer
Double myDbl = (Double) null; // yes it's possible, no error

任何含有null值的包装类在Java拆箱生成基本数据类型时候都会抛出一个空指针异常

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

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

Integer tt = null;
System.out.println((tt instanceof Integer) ? "true" : "false");


使用简单技巧避免空指针异常

1.使用equals()方法时,以已知字符串为基准
2.对于对象的字符串表示,使用String.valueof(obj)而不用obj.toString()
3.运用null安全方法
//StringUtils methods are null safe, they don't throw NullPointerException
System.out.println(StringUtils.isEmpty(null));//true
System.out.println(StringUtils.isBlank(null));//true
System.out.println(StringUtils.isNumeric(null));//false
System.out.println(StringUtils.isAllUpperCase(null));//false
4.方法避免直接返回null,采用Collections.EMPTY_LIST, Collections.EMPTY_SET and Collections.EMPTY_MAP 替代
5. 使用@NotNull、@Nullable注解
6.避免不必要的自动拆箱装箱
Person ram = new Person("ram");
int phone = ram.getPhone();
此时若getPhone为Integer类型且为空,会throw NullPointerException




原文地址:https://www.cnblogs.com/linux007/p/5777971.html