• String.valueOf(null) 报空指针


    String.valueOf 默认的方法

    argument 可以为null 的

    1. boolean b = null;
    2. char c = null;
    3. char[] data = null;
    4. double d = null;
    5. float f = null;
    6. int i = null;
    7. long l = null;
    8. Object obj = null;

    String.valueOf(null) 会调用更为具体valueOf(char[] data)

        /**
         * Returns the string representation of the <code>char</code> array
         * argument. The contents of the character array are copied; subsequent
         * modification of the character array does not affect the newly
         * created string.
         *
         * @param   data   a <code>char</code> array.
         * @return  a newly allocated string representing the same sequence of
         *          characters contained in the character array argument.
         */
        public static String valueOf(char data[]) {
            return new String(data);
        }
    
        /**
         * Allocates a new {@code String} so that it represents the sequence of
         * characters currently contained in the character array argument. The
         * contents of the character array are copied; subsequent modification of
         * the character array does not affect the newly created string.
         *
         * @param  value
         *         The initial value of the string
         */
        public String(char value[]) {
            this.value = Arrays.copyOf(value, value.length);
        }

    会在value.length 处抛空指针异常!

    case1:

    String.valueOf(null);

    case2:

    char[] data;

    String.valueOf(data);

  • 相关阅读:
    git学习记录——基础概念和文件的基本操作
    java 之 Properties 类
    java 之 Map类
    java 之 迭代器
    java 之 Collection类
    java 之日期时间操作
    java 之String类
    如何把ASP.NET MVC项目部署到本地IIS上
    [工具]Visual Studio
    [MVC][Shopping]Copy Will's Code
  • 原文地址:https://www.cnblogs.com/zno2/p/4545835.html
Copyright © 2020-2023  润新知