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

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

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

Output:null+1


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

    /**
     * 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();
    }

但若

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
+1

String的源代码:

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

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

这里写图片描述

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

这里写图片描述

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

这里写图片描述

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值