以例子为主
1. 变量为空, toString()
Object s =null;
System.out.println(s.toString());
2. 函数.equal 前的变量为null
Object s =null;
System.out.println(s.equals("a"));
3. .replace函数 ,第一个参数为空 或者 第二个参数为空
String s ="b";
String str =null;
String s1 =str.replace(str, s);
------------------------------------------------------------
String s =null;
String str ="a";
String s1 =str.replace(str, s);
4. equalsIgnoreCase函数,可将常量字符串放前面 防止出错。
String str =null;
if(str.equalsIgnoreCase("a")){ //改成 if("a".equalsIgnoreCase(str)) 即可
System.out.println("true");
}else{
System.out.println("false");
}
5.装箱拆箱导致错误
static Integer i ; public static void main(String[] args) { if(i==42){ System.out.println("aaa"); } }
打印结果也是java.lang.NullPointerException。
奇怪不:它运行到if语句时候抛出异常。问题在于,i是Integer类型,它的初始值为null;当程序在计算if(i==42)时候,它会将Integer和int进行比较,几乎在任何一种情况下,当在一项操作中混合使用 基本类型和装箱基本类型时,装箱基本类型就会自动拆箱。如果null对象引用被自动拆箱,就会得到一个java.lang.NullPointerException异常