引用的缺省值null

引用的缺省值null

引用也有缺省值一nul

  • null是引用类型的缺省值

  • null代表空,不存在。可以读作空

  • 引用类型的数组创建出来,初始值都是空

通过nul理解引用的“二级跳”

public class class_Null {
  public static void main(String[] args) {
      //数组在创建出来之后, 会按照类型给数组中的每个元素赋一个缺省值
      //引用类型的缺省值是null
      Merchandise[] merchandises = new Merchandise[9];
      //给索引为偶数的引用赋值
      for (int i = 0;i<merchandises.length;i++){
          if (i%2 == 0 ){
              merchandises[i] = new Merchandise();
          }
      }
      //依次输出数组的值
      for (int i = 0;i < merchandises.length;i++)
      {
          System.out.println(merchandises[i]);
      }
       
  }
}

输出结果 :
Merchandise@16d3586
null
Merchandise@154617c
null
Merchandise@a14482
null
Merchandise@140e19d
null
Merchandise@17327b6

Process finished with exit code 0
//可以发现 ,代码当中没有给数组赋值的奇数元素部分输出的值都是null ,即证明了初始的类型引用创建出来值都为null

 

nul带来的问题

  • 大名鼎鼎的NullPointerException(NPE)

  • 如果不确定,使用前要先判断引用是不是空

public class class_Notnull {
  public static void main(String[] args) {
      //数组在创建出来之后, 会按照类型给数组中的每个元素赋一个缺省值
      //引用类型的缺省值是null
      Merchandise[] merchandises = new Merchandise[9];
      //给索引为偶数的引用赋值
      for (int i = 0;i<merchandises.length;i++){
          merchandises[i] = new Merchandise();
      }
      //依次输出数组的值
      for (int i = 0;i < merchandises.length;i++)
      {
          System.out.println(merchandises[i]);
      }

      for (int i = 0;i < merchandises.length;i++) {
          if (merchandises[i] != null){
              //如果数组不为空, 就给数据赋一个值
              merchandises[i].name = "商品" + i;
          }
      }

      for (int i = 0;i < merchandises.length;i++) {
          if (merchandises[i] != null){
              //如果数组不为空, 就将数组打印出来
              System.out.println(merchandises[i].name);
          }
      }

  }
}
posted @ 2022-04-16 16:33  comia  阅读(81)  评论(0)    收藏  举报