zoukankan      html  css  js  c++  java
  • 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




  • 相关阅读:
    python微信机器人
    爬取糗事百科,微信自动发送
    验证码破解
    [Python]机器学习【推荐】
    [Python]利用jieba.analyse进行 关键词 提取
    《将博客搬至CSDN》
    [极限测试]第一日进度
    [Python]调用百度API进行自然语言处理 标签、关键字 以及 词法分析
    学习进度报告【第三周】
    [Python]调用百度地图API对地点进行搜索,利用 JSON 返回纬度/行政区域编号
  • 原文地址:https://www.cnblogs.com/linux007/p/5777971.html
Copyright © 2011-2022 走看看