【问题标题】:Why String concat(String) method is acting differently? [duplicate]为什么 String concat(String) 方法的行为不同? [复制]
【发布时间】:2019-02-12 15:29:43
【问题描述】:

我请检查下面的代码。

我可以理解没有分配字符串 s1,因此即使使用了 concat(string) 方法,它也会给出原始输出。

但是,在 String s2 的情况下,没有分配变量,但连接有效。

谁能解释一下?

package com.stringconcat.main;

public class StringConcat {

    public static void main(String[] args) {

        String  s1 = "Hello";
        s1.concat(" World");
        System.out.println("String s1 output: " + s1);

        String s2 = "Hello" /*s1*/;
        System.out.println("String s2 output: " + s2.concat(" World"));
    }
}

输出是: 字符串 s1 输出:你好 字符串 s2 输出:Hello World

【问题讨论】:

  • System.out.println("String s2 output: " + s2.concat(" World")); 基本上是String temp1 = "String s2 output: "; String temp2 = s2.concat(" World "); System.out.println(temp1 + temp2);
  • 谢谢哥们!!对不起,我的错,我错过了!!
  • 好的,伙计们!!!我的坏,我的错误!很抱歉我错过了它,并感谢那些只关心消除混乱并尽其所能提供帮助的好人!如果有人生气,我再次道歉。如果这没有帮助你自己!
  • @AbhiroopNandiRay 认真地删除此评论。您将被标记并很可能从 stackoverflow 中删除,此外这很粗鲁......就像超级粗鲁

标签: java string immutability concat


【解决方案1】:

因为在第二种情况下,您将s2.concat(" World")结果 连接到"String s2 output: ",所以您不会忽略它。

【讨论】:

  • 谢谢!!!对不起,我错过了!
  • @AbhiroopNandiRay 没关系...
【解决方案2】:

Concat 返回一个包含连接字符串的新 String 实例。您只需通过不将其分配给变量来删除此串联版本。

【讨论】:

  • 我已经从某个好人那里得到了答案。谢谢你想说的话。
【解决方案3】:

这是因为s1Hellos2.concat(" World") 是另一个 string 对象,其连接字符串为Hello Worldconcat#string 方法总是返回带有连接字符串的 string 对象的新实例。

【讨论】:

    猜你喜欢
    • 2014-04-11
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    • 2019-11-19
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2016-02-03
    相关资源
    最近更新 更多