将创建多少个 String 实例?

How many instances of String will be created?

这段代码的结果:

public class Test {
    public static void main(String[] args) {
        String s = "Java";
        s.concat(" SE 6");
        s.replace('6', '7');
        System.out.print(s);
    }
}

将是"Java" 谁能告诉我在执行过程中会创建多少个String实例?

字符串在 Java 中是不可变的。尽管您在其上调用方法,但它们每次 returns 一个新字符串。

这里创建了4个实例

请关注评论:

    String s = "Java";   // 1
    s.concat(" SE 6");   // 2 & 3 for concat method returns a new string  and  another literal created " SE 6"
    s.replace('6', '7'); // 4 returns a new string instance  which you are not receiving
    System.out.print(s);