今天在刷【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”