public class Demo0 {
public static void main(String[] args){
String s = "welcome";
s += " to";
s.concat(" java");//为什么没有连接上呢? 我的困惑之处;
System.out.println(s);//输出 welcome to
System.out.println(s.concat(" 2java"));
//输出 welcome to 2java ,这时候为什么就连接上了呢?
}
}
java
public static void main(String[] args){
String s = "welcome";
s += " to";
s.concat(" java");//为什么没有连接上呢? 我的困惑之处;
System.out.println(s);//输出 welcome to
System.out.println(s.concat(" 2java"));
//输出 welcome to 2java ,这时候为什么就连接上了呢?
}
}
java
这是String 那个方法,它是返回一个连接好的字符串。OK?
s=s.concat(" java");
这个是concat的源代码
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
char buf[] = new char[count + otherLen];
getChars(0, count, buf, 0);
str.getChars(0, otherLen, buf, count);
return new String(0, count + otherLen, buf);
}
这句话返回s和" java"拼接后的字符串,可是你却没有用。
应该改成s=s.concat(" java");
public static void main(String[] args){
String s = "welcome"; // 对象1
s += " to"; //改变对象1缓冲池的值
s.concat(" java");//为什么没有连接上呢? 我的困惑之处; //生成对象2
System.out.println(s);//输出 welcome to //输出对象1 System.out.println(s.concat(" 2java")); //输出对象3
//输出 welcome to 2java ,这时候为什么就连接上了呢?
}
}只要记住一点 对象是新生成的还是 被改变了就行了
s=s.concat(" java");
就是改变如果要探究原因,还是看看java缓冲池相关的概念内容