关于string的拼接


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 
}
  1. String s1 = "javaEE";String s2 = "hadoop"; 在字符串池中创建两个字符串对象。
  2. String s3 = "javaEEhadoop"; 在字符串池中创建一个字符串对象。
  3. String s4 = "javaEE" + "hadoop"; 这是编译期优化,Java 编译器会在编译时将字符串常量拼接成一个新的常量。由于这里的拼接都是字符串常量,所以 s4 会指向字符串池中的 "javaEEhadoop",因此 s3 == s4 为 true。

然而,接下来的比较涉及变量:

  1. String s5 = s1 + "hadoop"; 这里 s1 是一个变量,而不是编译期的常量,所以编译器不能在编译时优化它。因此,s5 会在运行时通过字符串拼接创建一个新的字符串对象,它不会与之前的 "javaEEhadoop" 对象相同,所以 s3 == s5 为 false。

  2. String s6 = "javaEE" + s2; 这里 s2 是一个变量,同样无法在编译时优化。因此,s6 会在运行时通过字符串拼接创建一个新的字符串对象,它也不会与之前的 "javaEEhadoop" 对象相同,所以 s3 == s6 为 false。

  3. String s7 = s1 + s2; 这里涉及两个变量 s1s2 的拼接,同样不能在编译时优化。因此,s7 会在运行时通过字符串拼接创建一个新的字符串对象,它也不会与之前的 "javaEEhadoop" 对象相同,所以 s3 == s7 为 false。

接下来比较这些变量:

  1. System.out.println(s5 == s6); 由于 s5s6 都是通过运行时拼接得到的新字符串对象,它们指向不同的对象实例,所以 s5 == s6 为 false。

  2. System.out.println(s5 == s7); 同样地,s5s7 也都是通过运行时拼接得到的不同字符串对象,所以 s5 == s7 为 false。

  3. System.out.println(s6 == s7); 同样地,s6s7 也都是通过运行时拼接得到的不同字符串对象,所以 s6 == s7 为 false。

最后,String s8 = s6.intern();s6 字符串调用 intern() 方法,该方法会尝试将字符串添加到字符串常量池中(如果常量池中已经存在相同内容的字符串,则返回常量池中的引用)。在这里,因为常量池中已经有了 "javaEEhadoop" 字符串,所以 s8 会指向常量池中的 "javaEEhadoop" 对象。因此,s3 == s8 为 true。

  • 帮你找了个相似的问题, 你可以看下: https://ask.csdn.net/questions/7445150
  • 我还给你找了一篇非常好的博客,你可以看看是否有帮助,链接:String类的特点
  • 除此之外, 这篇博客: 字符流,转换流,string中的编解码问题中的 字符缓冲流的特殊功能复制文本文件 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • 在这里插入图片描述

  • 以下回答由chatgpt基于相关博客总结生成:

    在Python中,拼接两个字符串可以使用多种方法。下面是几种常用的方法:

    1. 使用"+"操作符
    string1 = "Hello"
    string2 = "World"
    result = string1 + " " + string2
    print(result)
    

    输出结果为:"Hello World"

    1. 使用字符串的join()方法
    string1 = "Hello"
    string2 = "World"
    result = " ".join([string1, string2])
    print(result)
    

    输出结果为:"Hello World"

    1. 使用f-string
    string1 = "Hello"
    string2 = "World"
    result = f"{string1} {string2}"
    print(result)
    

    输出结果为:"Hello World"

    1. 使用字符串的format()方法
    string1 = "Hello"
    string2 = "World"
    result = "{} {}".format(string1, string2)
    print(result)
    

    输出结果为:"Hello World"

    以上是常见的几种拼接字符串的方法,你可以根据自己的需要选择适合的方式。