一个字符串为空时再去链接另外一个字符(串)

今天在刷【LeetCode】题的时候,遇到一个问题:java

public class Solution {
    public static void main(String[]args){
        String str=null;
        str+="+1";
        System.out.println(str);
    }
}

Output:null+1web


我是要解决字符串转型为整型,却遇到了这个有趣的问题,因此只能加了一些步骤去解决。
介此我特地去查看了一下Java的源代码:svg

/** * Returns the string representation of the {@code Object} argument. * * @param obj an {@code Object}. * @return if the argument is {@code null}, then a string equal to * {@code "null"}; otherwise, the value of * {@code obj.toString()} is returned. * @see java.lang.Object#toString() */
    public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }

但若this

public class Solution {
    public static void main(String[]args){
        String str=null;
        str+="+1";
        System.out.println(str);
        String str2="";
        str2+="+1";
        System.out.println(str2);
    }
}

Output:
null+1
+1spa

String的源代码:code

public String() {
        this.value = "".value;
    }

后来继续查找了些资料,并结合了两个字符串的内容,了解到
String str=null:则str并无被实例化,并无申请空间xml

这里写图片描述

String str=“”:str已被实例化,内容为“”blog

这里写图片描述

因此得出最以前输出“null+1”的结论:
String str=null;
str+=1;//这里先去实例化str;但根据第一个源代码,参数为null,因此把字符串“null”赋给了str,再去加上“+1”图片

这里写图片描述