public static void test5() {
String s1 = "javaEE";
String s2 = "hadoop";
String s3 = "javaEEhadoop";
String s4 = "javaEE" + "hadoop";
String s5 = s1 + "hadoop";
String s6 = "javaEE" + s2;
String s7 = s1 + s2;
System.out.println(s3 == s4); // true
System.out.println(s3 == s5); // false
System.out.println(s3 == s6); // false
System.out.println(s3 == s7); // false
System.out.println(s5 == s6); // false
System.out.println(s5 == s7); // false
System.out.println(s6 == s7); // false
String s8 = s6.intern();
System.out.println(s3 == s8); // true
}
String s1 = "javaEE";
和 String s2 = "hadoop";
在字符串池中创建两个字符串对象。String s3 = "javaEEhadoop";
在字符串池中创建一个字符串对象。String s4 = "javaEE" + "hadoop";
这是编译期优化,Java 编译器会在编译时将字符串常量拼接成一个新的常量。由于这里的拼接都是字符串常量,所以 s4
会指向字符串池中的 "javaEEhadoop"
,因此 s3 == s4
为 true。然而,接下来的比较涉及变量:
String s5 = s1 + "hadoop";
这里 s1
是一个变量,而不是编译期的常量,所以编译器不能在编译时优化它。因此,s5
会在运行时通过字符串拼接创建一个新的字符串对象,它不会与之前的 "javaEEhadoop"
对象相同,所以 s3 == s5
为 false。
String s6 = "javaEE" + s2;
这里 s2
是一个变量,同样无法在编译时优化。因此,s6
会在运行时通过字符串拼接创建一个新的字符串对象,它也不会与之前的 "javaEEhadoop"
对象相同,所以 s3 == s6
为 false。
String s7 = s1 + s2;
这里涉及两个变量 s1
和 s2
的拼接,同样不能在编译时优化。因此,s7
会在运行时通过字符串拼接创建一个新的字符串对象,它也不会与之前的 "javaEEhadoop"
对象相同,所以 s3 == s7
为 false。
接下来比较这些变量:
System.out.println(s5 == s6);
由于 s5
和 s6
都是通过运行时拼接得到的新字符串对象,它们指向不同的对象实例,所以 s5 == s6
为 false。
System.out.println(s5 == s7);
同样地,s5
和 s7
也都是通过运行时拼接得到的不同字符串对象,所以 s5 == s7
为 false。
System.out.println(s6 == s7);
同样地,s6
和 s7
也都是通过运行时拼接得到的不同字符串对象,所以 s6 == s7
为 false。
最后,String s8 = s6.intern();
将 s6
字符串调用 intern()
方法,该方法会尝试将字符串添加到字符串常量池中(如果常量池中已经存在相同内容的字符串,则返回常量池中的引用)。在这里,因为常量池中已经有了 "javaEEhadoop"
字符串,所以 s8
会指向常量池中的 "javaEEhadoop"
对象。因此,s3 == s8
为 true。
在Python中,拼接两个字符串可以使用多种方法。下面是几种常用的方法:
string1 = "Hello"
string2 = "World"
result = string1 + " " + string2
print(result)
输出结果为:"Hello World"
string1 = "Hello"
string2 = "World"
result = " ".join([string1, string2])
print(result)
输出结果为:"Hello World"
string1 = "Hello"
string2 = "World"
result = f"{string1} {string2}"
print(result)
输出结果为:"Hello World"
string1 = "Hello"
string2 = "World"
result = "{} {}".format(string1, string2)
print(result)
输出结果为:"Hello World"
以上是常见的几种拼接字符串的方法,你可以根据自己的需要选择适合的方式。