Is “new String()” immutable as well?

后端 未结 15 2506
日久生厌
日久生厌 2020-12-12 23:43

I\'ve been studying Java String for a while. The following questions are based on the below posts

Java String is special
Immutability of String in java

15条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-12 23:58

    1) Immutability: String will be immutable if you create it using new or other way for security reasons

    2) Yes there will be a empty entry in the string pool.

    You can better understand the concept using the code

        String s1 = new String("Test");
        String s2 = new String("Test");
        String s3 = "Test";
        String s4 = "Test";
    
        System.out.println(s1==s2);//false
        System.out.println(s1==s3);//false
        System.out.println(s2==s3);//false
        System.out.println(s4==s3);//true
    

    Hope this will help your query. You can always check the source code for String class in case of better understanding Link : http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/String.java

提交回复
热议问题