som*_*har 17 java string concat
这段代码:
String s = "TEST";
String s2 = s.trim();
s.concat("ING");
System.out.println("S = "+s);
System.out.println("S2 = "+s2);
Run Code Online (Sandbox Code Playgroud)
结果输出:
S = TEST
S2 = TEST
BUILD SUCCESSFUL (total time: 0 seconds)
Run Code Online (Sandbox Code Playgroud)
为什么"TEST"和"ING"没有连接在一起?
nos*_*nos 47
String是不可变的,这意味着您无法在Java中更改String.concat()返回一个新的连接字符串.
String s = "TEST";
String s2 = s.trim();
String s3 = s.concat("ING");
System.out.println("S = "+s);
System.out.println("S2 = "+s2);
System.out.println("S3 = "+s3);
Run Code Online (Sandbox Code Playgroud)
因为String
是不可变的 - 类String
不包含改变String
对象本身内容的方法.该concat()
方法返回一个String
包含操作结果的new .而不是这个:
s.concat("ING");
Run Code Online (Sandbox Code Playgroud)
试试这个:
s = s.concat("ING");
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
21177 次 |
最近记录: |