When should we use intern method of String on String literals

后端 未结 14 966
生来不讨喜
生来不讨喜 2020-11-22 08:11

According to String#intern(), intern method is supposed to return the String from the String pool if the String is found in String pool, otherwise a new string

14条回答
  •  日久生厌
    2020-11-22 08:21

    String s1 = "Anish";
            String s2 = "Anish";
    
            String s3 = new String("Anish");
    
            /*
             * When the intern method is invoked, if the pool already contains a
             * string equal to this String object as determined by the
             * method, then the string from the pool is
             * returned. Otherwise, this String object is added to the
             * pool and a reference to this String object is returned.
             */
            String s4 = new String("Anish").intern();
            if (s1 == s2) {
                System.out.println("s1 and s2 are same");
            }
    
            if (s1 == s3) {
                System.out.println("s1 and s3 are same");
            }
    
            if (s1 == s4) {
                System.out.println("s1 and s4 are same");
            }
    

    OUTPUT

    s1 and s2 are same
    s1 and s4 are same
    

提交回复
热议问题