null的问题

这个可以作为上一篇npe的一个补充,这里主要说的是String中的null值问题:
1.toString()和System.out.println()

  String str = null;
  str.toString(); // 2
  System.out.println(str); //3

2行报错NPE,3行正常执行结果是null。
注:推荐使用强转(String)str代替str.toString()。
2.null和连接符"+"一起的情况

    String a = null;
    String b = a + "1"; 
    System.out.println(b);

输出结果是"null1"。
3.map中的containsKey(key)和null != map.get(key)区别
这个要看map是什么类型的map(如HashMap),是否支持value为null的键值对

    Map map = Maps.newHashMap();
    map.put("id", null);
    boolean f1 = null != map.get("id"); //false
    boolean f2 = map.containsKey("id"); //true
    Map map = Maps.newHashMap();
    boolean f1 = null != map.get("id"); //false
    boolean f2 = map.containsKey("id"); //false

4.静态方法和普通方法

public class Mas {

  public static void init() {
    System.out.println("init...");
  }

  public void show() {
    System.out.println("show...");
  }

}
  public static void main(String[] args) {
    Mas mas = null;
    mas.init(); //1
    mas.show(); //2
  }

1正常,2报NPE

你可能感兴趣的:(null的问题)