The return of String.intern() explainedWhat is Java String interning?How to print the whole String pool?When...

Is there a nicer/politer/more positive alternative for "negates"?

Why is so much work done on numerical verification of the Riemann Hypothesis?

What features enable the Su-25 Frogfoot to operate with such a wide variety of fuels?

What does Apple's new App Store requirement mean

How does electrical safety system work on ISS?

Change the color of a single dot in `ddot` symbol

What is the highest possible scrabble score for placing a single tile

How to make money from a browser who sees 5 seconds into the future of any web page?

Is this part of the description of the Archfey warlock's Misty Escape feature redundant?

What does "Scientists rise up against statistical significance" mean? (Comment in Nature)

How can ping know if my host is down

How would you translate "more" for use as an interface button?

Does the reader need to like the PoV character?

How much theory knowledge is actually used while playing?

Short story about a deaf man, who cuts people tongues

Has the laser at Magurele, Romania reached a tenth of the Sun's power?

Non-trope happy ending?

"It doesn't matter" or "it won't matter"?

Pre-mixing cryogenic fuels and using only one fuel tank

Has any country ever had 2 former presidents in jail simultaneously?

Which Article Helped Get Rid of Technobabble in RPGs?

Strong empirical falsification of quantum mechanics based on vacuum energy density?

Is there a RAID 0 Equivalent for RAM?

Why should universal income be universal?



The return of String.intern() explained


What is Java String interning?How to print the whole String pool?When should we use intern method of String on String literalsWhy is there no String.Empty in Java?String.intern() thread safety guaranteed?What is the purpose of Java's String.intern()?String.intern() how to workJava 1.7 String.intern() is not InternedStrings in JVM or i am wrongJava: How exactly String intern() and StringPool works?String intern() behaviourDoes intern() ever create a literal in the pool?Is String Pool really empty initially as mentioned in the Javadoc of String.intern() method?













18















Consider:



String s1 = new StringBuilder("Cattie").append(" & Doggie").toString();
System.out.println(s1.intern() == s1); // true why?
System.out.println(s1 == "Cattie & Doggie"); // true another why?

String s2 = new StringBuilder("ja").append("va").toString();
System.out.println(s2.intern() == s2); // false

String s3 = new String("Cattie & Doggie");
System.out.println(s3.intern() == s3); // false
System.out.println(s3 == "Cattie & Doggie"); // false


I got confused why they are resulting differently by the returned value of String.intern() which says:




When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) 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.




Especially after these two tests:



assertFalse("new String() should create a new instance", new String("jav") == "jav");
assertFalse("new StringBuilder() should create a new instance",
new StringBuilder("jav").toString() == "jav");


I once read a post talking about some special strings interned before everything else, but it's a real blur now.



If there are some strings pre-interned, is there a way to get kind of a list of them? I am just curious about what they can be.





Updated



Thanks to the help of @Eran and @Slaw, I finally can explain what just happened there for the output



true
true
false
false
false



  1. Since "Cattie & Doggie" doesn't exist in the pool, s1.intern() will put the current object reference to the pool and return itself, so s1.intern() == s1;


  2. "Cattie & Doggie" already in the pool now, so string literal "Cattie & Doggie" will just use the reference in pool which is actually s1, so again we have true;


  3. new StringBuilder().toString() will create a new instance while "java" is already in the pool and then the reference in pool will be returned when calling s2.intern(), so s2.intern() != s2 and we have false;


  4. new String() will also return a new instance, but when we try to s3.intern(), it will return the previously stored reference in the pool which is actualy s1 so s3.intern() != s3 and we have false;

  5. As #2 already discussed, String literal "Cattie & Doggie" will return the reference already stored in the pool (which is actually s1), so s3 != "Cattie & Doggie" and we have false again.


Thanks for @Sunny to provide a trick to get all the interned strings.










share|improve this question





























    18















    Consider:



    String s1 = new StringBuilder("Cattie").append(" & Doggie").toString();
    System.out.println(s1.intern() == s1); // true why?
    System.out.println(s1 == "Cattie & Doggie"); // true another why?

    String s2 = new StringBuilder("ja").append("va").toString();
    System.out.println(s2.intern() == s2); // false

    String s3 = new String("Cattie & Doggie");
    System.out.println(s3.intern() == s3); // false
    System.out.println(s3 == "Cattie & Doggie"); // false


    I got confused why they are resulting differently by the returned value of String.intern() which says:




    When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) 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.




    Especially after these two tests:



    assertFalse("new String() should create a new instance", new String("jav") == "jav");
    assertFalse("new StringBuilder() should create a new instance",
    new StringBuilder("jav").toString() == "jav");


    I once read a post talking about some special strings interned before everything else, but it's a real blur now.



    If there are some strings pre-interned, is there a way to get kind of a list of them? I am just curious about what they can be.





    Updated



    Thanks to the help of @Eran and @Slaw, I finally can explain what just happened there for the output



    true
    true
    false
    false
    false



    1. Since "Cattie & Doggie" doesn't exist in the pool, s1.intern() will put the current object reference to the pool and return itself, so s1.intern() == s1;


    2. "Cattie & Doggie" already in the pool now, so string literal "Cattie & Doggie" will just use the reference in pool which is actually s1, so again we have true;


    3. new StringBuilder().toString() will create a new instance while "java" is already in the pool and then the reference in pool will be returned when calling s2.intern(), so s2.intern() != s2 and we have false;


    4. new String() will also return a new instance, but when we try to s3.intern(), it will return the previously stored reference in the pool which is actualy s1 so s3.intern() != s3 and we have false;

    5. As #2 already discussed, String literal "Cattie & Doggie" will return the reference already stored in the pool (which is actually s1), so s3 != "Cattie & Doggie" and we have false again.


    Thanks for @Sunny to provide a trick to get all the interned strings.










    share|improve this question



























      18












      18








      18


      0






      Consider:



      String s1 = new StringBuilder("Cattie").append(" & Doggie").toString();
      System.out.println(s1.intern() == s1); // true why?
      System.out.println(s1 == "Cattie & Doggie"); // true another why?

      String s2 = new StringBuilder("ja").append("va").toString();
      System.out.println(s2.intern() == s2); // false

      String s3 = new String("Cattie & Doggie");
      System.out.println(s3.intern() == s3); // false
      System.out.println(s3 == "Cattie & Doggie"); // false


      I got confused why they are resulting differently by the returned value of String.intern() which says:




      When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) 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.




      Especially after these two tests:



      assertFalse("new String() should create a new instance", new String("jav") == "jav");
      assertFalse("new StringBuilder() should create a new instance",
      new StringBuilder("jav").toString() == "jav");


      I once read a post talking about some special strings interned before everything else, but it's a real blur now.



      If there are some strings pre-interned, is there a way to get kind of a list of them? I am just curious about what they can be.





      Updated



      Thanks to the help of @Eran and @Slaw, I finally can explain what just happened there for the output



      true
      true
      false
      false
      false



      1. Since "Cattie & Doggie" doesn't exist in the pool, s1.intern() will put the current object reference to the pool and return itself, so s1.intern() == s1;


      2. "Cattie & Doggie" already in the pool now, so string literal "Cattie & Doggie" will just use the reference in pool which is actually s1, so again we have true;


      3. new StringBuilder().toString() will create a new instance while "java" is already in the pool and then the reference in pool will be returned when calling s2.intern(), so s2.intern() != s2 and we have false;


      4. new String() will also return a new instance, but when we try to s3.intern(), it will return the previously stored reference in the pool which is actualy s1 so s3.intern() != s3 and we have false;

      5. As #2 already discussed, String literal "Cattie & Doggie" will return the reference already stored in the pool (which is actually s1), so s3 != "Cattie & Doggie" and we have false again.


      Thanks for @Sunny to provide a trick to get all the interned strings.










      share|improve this question
















      Consider:



      String s1 = new StringBuilder("Cattie").append(" & Doggie").toString();
      System.out.println(s1.intern() == s1); // true why?
      System.out.println(s1 == "Cattie & Doggie"); // true another why?

      String s2 = new StringBuilder("ja").append("va").toString();
      System.out.println(s2.intern() == s2); // false

      String s3 = new String("Cattie & Doggie");
      System.out.println(s3.intern() == s3); // false
      System.out.println(s3 == "Cattie & Doggie"); // false


      I got confused why they are resulting differently by the returned value of String.intern() which says:




      When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) 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.




      Especially after these two tests:



      assertFalse("new String() should create a new instance", new String("jav") == "jav");
      assertFalse("new StringBuilder() should create a new instance",
      new StringBuilder("jav").toString() == "jav");


      I once read a post talking about some special strings interned before everything else, but it's a real blur now.



      If there are some strings pre-interned, is there a way to get kind of a list of them? I am just curious about what they can be.





      Updated



      Thanks to the help of @Eran and @Slaw, I finally can explain what just happened there for the output



      true
      true
      false
      false
      false



      1. Since "Cattie & Doggie" doesn't exist in the pool, s1.intern() will put the current object reference to the pool and return itself, so s1.intern() == s1;


      2. "Cattie & Doggie" already in the pool now, so string literal "Cattie & Doggie" will just use the reference in pool which is actually s1, so again we have true;


      3. new StringBuilder().toString() will create a new instance while "java" is already in the pool and then the reference in pool will be returned when calling s2.intern(), so s2.intern() != s2 and we have false;


      4. new String() will also return a new instance, but when we try to s3.intern(), it will return the previously stored reference in the pool which is actualy s1 so s3.intern() != s3 and we have false;

      5. As #2 already discussed, String literal "Cattie & Doggie" will return the reference already stored in the pool (which is actually s1), so s3 != "Cattie & Doggie" and we have false again.


      Thanks for @Sunny to provide a trick to get all the interned strings.







      java string-interning






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 13 at 14:24









      John Kugelman

      246k54406459




      246k54406459










      asked Mar 13 at 6:50









      HearenHearen

      2,7841428




      2,7841428
























          3 Answers
          3






          active

          oldest

          votes


















          27














          s2.intern() would return the instance referenced by s2 only if the String pool didn't contain a String whose value is "java" prior to that call. The JDK classes intern some Strings before your code is executed. "java" must be one of them. Therefore, s2.intern() returns the previously interned instance instead of s2.



          On the other hand, the JDK classes did not intern any String whose value is equal to "Cattie & Doggie", so s1.intern() returns s1.



          I am not aware of any list of pre-interned Strings. Such a list will most likely be considered an implementation detail, which may vary on different JDK implementations and JDK versions, and should not be relied on.






          share|improve this answer


























          • thank you for the detailed explanation, so is it correct to say: s.intern() will return the original reference if the string is not interned but if it's already interned (in the constant pool) then it returns the reference in the constant pool?

            – Hearen
            Mar 13 at 7:06











          • @Hearen that's true, as the javadoc says - "When the intern method is invoked, if the pool already contains a string equal to this String object as determined bythe equals(Object) 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. "

            – Eran
            Mar 13 at 7:08











          • sorry to disrupt you again. If that's so then why the second why still returns a true? ... so confusing now... but when I replaced the new StringBuilder().toString() with new String() both of them will become false. So weird...

            – Hearen
            Mar 13 at 7:13








          • 2





            "any list of pre-interned Strings" would depend on which JDK classes your program happened to load as well.

            – Alexey Romanov
            Mar 13 at 8:13






          • 2





            @AlexeyRomanov and the launcher, e.g. the commonly used standard launcher loads the specfied main class and does a getMethod("main", String[].class) on it, thus “pre-interning” the string "main". A different launcher, e.g. a native launcher invoking the main method via JNI would behave differently. Likewise, the way command line options are processed may differ and hence, have different effect on the list of “pre-interned” strings.

            – Holger
            Mar 13 at 8:51





















          3














          When the intern() method is invoked on a String object it looks the string contained by this String object in the pool, if the string is found there 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.



          So java string must already be in the pool. hence it is giving false.



          You can print all strings in pool



          How to print the whole String pool?



          Here is an example to get all string if you are using openjdk.






          share|improve this answer


























          • I just tried with the example in github you enclosed, it seems not working though I added the dependency it requires $JAVA_HOME/lib/sa-jdi.jar. As for the OS link, How to print the whole String pool?, it's not tested yet but looks so tricky. Thanks for the help :)

            – Hearen
            Mar 13 at 10:53





















          0














          String literals (those that are hardcoded like "a string") are already interned for you by the compiler. But those strings that are acquired programmatically are not, and will be interned only if you use .intern() method.



          Usually you don't intern strings manually, unless you know you will store in memory a large number of repeating strings, so you can save a lot of memory that way.



          That is explained here:
          What is Java String interning?






          share|improve this answer

























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55135968%2fthe-return-of-string-intern-explained%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            3 Answers
            3






            active

            oldest

            votes








            3 Answers
            3






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            27














            s2.intern() would return the instance referenced by s2 only if the String pool didn't contain a String whose value is "java" prior to that call. The JDK classes intern some Strings before your code is executed. "java" must be one of them. Therefore, s2.intern() returns the previously interned instance instead of s2.



            On the other hand, the JDK classes did not intern any String whose value is equal to "Cattie & Doggie", so s1.intern() returns s1.



            I am not aware of any list of pre-interned Strings. Such a list will most likely be considered an implementation detail, which may vary on different JDK implementations and JDK versions, and should not be relied on.






            share|improve this answer


























            • thank you for the detailed explanation, so is it correct to say: s.intern() will return the original reference if the string is not interned but if it's already interned (in the constant pool) then it returns the reference in the constant pool?

              – Hearen
              Mar 13 at 7:06











            • @Hearen that's true, as the javadoc says - "When the intern method is invoked, if the pool already contains a string equal to this String object as determined bythe equals(Object) 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. "

              – Eran
              Mar 13 at 7:08











            • sorry to disrupt you again. If that's so then why the second why still returns a true? ... so confusing now... but when I replaced the new StringBuilder().toString() with new String() both of them will become false. So weird...

              – Hearen
              Mar 13 at 7:13








            • 2





              "any list of pre-interned Strings" would depend on which JDK classes your program happened to load as well.

              – Alexey Romanov
              Mar 13 at 8:13






            • 2





              @AlexeyRomanov and the launcher, e.g. the commonly used standard launcher loads the specfied main class and does a getMethod("main", String[].class) on it, thus “pre-interning” the string "main". A different launcher, e.g. a native launcher invoking the main method via JNI would behave differently. Likewise, the way command line options are processed may differ and hence, have different effect on the list of “pre-interned” strings.

              – Holger
              Mar 13 at 8:51


















            27














            s2.intern() would return the instance referenced by s2 only if the String pool didn't contain a String whose value is "java" prior to that call. The JDK classes intern some Strings before your code is executed. "java" must be one of them. Therefore, s2.intern() returns the previously interned instance instead of s2.



            On the other hand, the JDK classes did not intern any String whose value is equal to "Cattie & Doggie", so s1.intern() returns s1.



            I am not aware of any list of pre-interned Strings. Such a list will most likely be considered an implementation detail, which may vary on different JDK implementations and JDK versions, and should not be relied on.






            share|improve this answer


























            • thank you for the detailed explanation, so is it correct to say: s.intern() will return the original reference if the string is not interned but if it's already interned (in the constant pool) then it returns the reference in the constant pool?

              – Hearen
              Mar 13 at 7:06











            • @Hearen that's true, as the javadoc says - "When the intern method is invoked, if the pool already contains a string equal to this String object as determined bythe equals(Object) 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. "

              – Eran
              Mar 13 at 7:08











            • sorry to disrupt you again. If that's so then why the second why still returns a true? ... so confusing now... but when I replaced the new StringBuilder().toString() with new String() both of them will become false. So weird...

              – Hearen
              Mar 13 at 7:13








            • 2





              "any list of pre-interned Strings" would depend on which JDK classes your program happened to load as well.

              – Alexey Romanov
              Mar 13 at 8:13






            • 2





              @AlexeyRomanov and the launcher, e.g. the commonly used standard launcher loads the specfied main class and does a getMethod("main", String[].class) on it, thus “pre-interning” the string "main". A different launcher, e.g. a native launcher invoking the main method via JNI would behave differently. Likewise, the way command line options are processed may differ and hence, have different effect on the list of “pre-interned” strings.

              – Holger
              Mar 13 at 8:51
















            27












            27








            27







            s2.intern() would return the instance referenced by s2 only if the String pool didn't contain a String whose value is "java" prior to that call. The JDK classes intern some Strings before your code is executed. "java" must be one of them. Therefore, s2.intern() returns the previously interned instance instead of s2.



            On the other hand, the JDK classes did not intern any String whose value is equal to "Cattie & Doggie", so s1.intern() returns s1.



            I am not aware of any list of pre-interned Strings. Such a list will most likely be considered an implementation detail, which may vary on different JDK implementations and JDK versions, and should not be relied on.






            share|improve this answer















            s2.intern() would return the instance referenced by s2 only if the String pool didn't contain a String whose value is "java" prior to that call. The JDK classes intern some Strings before your code is executed. "java" must be one of them. Therefore, s2.intern() returns the previously interned instance instead of s2.



            On the other hand, the JDK classes did not intern any String whose value is equal to "Cattie & Doggie", so s1.intern() returns s1.



            I am not aware of any list of pre-interned Strings. Such a list will most likely be considered an implementation detail, which may vary on different JDK implementations and JDK versions, and should not be relied on.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 13 at 7:01

























            answered Mar 13 at 6:54









            EranEran

            289k37475561




            289k37475561













            • thank you for the detailed explanation, so is it correct to say: s.intern() will return the original reference if the string is not interned but if it's already interned (in the constant pool) then it returns the reference in the constant pool?

              – Hearen
              Mar 13 at 7:06











            • @Hearen that's true, as the javadoc says - "When the intern method is invoked, if the pool already contains a string equal to this String object as determined bythe equals(Object) 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. "

              – Eran
              Mar 13 at 7:08











            • sorry to disrupt you again. If that's so then why the second why still returns a true? ... so confusing now... but when I replaced the new StringBuilder().toString() with new String() both of them will become false. So weird...

              – Hearen
              Mar 13 at 7:13








            • 2





              "any list of pre-interned Strings" would depend on which JDK classes your program happened to load as well.

              – Alexey Romanov
              Mar 13 at 8:13






            • 2





              @AlexeyRomanov and the launcher, e.g. the commonly used standard launcher loads the specfied main class and does a getMethod("main", String[].class) on it, thus “pre-interning” the string "main". A different launcher, e.g. a native launcher invoking the main method via JNI would behave differently. Likewise, the way command line options are processed may differ and hence, have different effect on the list of “pre-interned” strings.

              – Holger
              Mar 13 at 8:51





















            • thank you for the detailed explanation, so is it correct to say: s.intern() will return the original reference if the string is not interned but if it's already interned (in the constant pool) then it returns the reference in the constant pool?

              – Hearen
              Mar 13 at 7:06











            • @Hearen that's true, as the javadoc says - "When the intern method is invoked, if the pool already contains a string equal to this String object as determined bythe equals(Object) 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. "

              – Eran
              Mar 13 at 7:08











            • sorry to disrupt you again. If that's so then why the second why still returns a true? ... so confusing now... but when I replaced the new StringBuilder().toString() with new String() both of them will become false. So weird...

              – Hearen
              Mar 13 at 7:13








            • 2





              "any list of pre-interned Strings" would depend on which JDK classes your program happened to load as well.

              – Alexey Romanov
              Mar 13 at 8:13






            • 2





              @AlexeyRomanov and the launcher, e.g. the commonly used standard launcher loads the specfied main class and does a getMethod("main", String[].class) on it, thus “pre-interning” the string "main". A different launcher, e.g. a native launcher invoking the main method via JNI would behave differently. Likewise, the way command line options are processed may differ and hence, have different effect on the list of “pre-interned” strings.

              – Holger
              Mar 13 at 8:51



















            thank you for the detailed explanation, so is it correct to say: s.intern() will return the original reference if the string is not interned but if it's already interned (in the constant pool) then it returns the reference in the constant pool?

            – Hearen
            Mar 13 at 7:06





            thank you for the detailed explanation, so is it correct to say: s.intern() will return the original reference if the string is not interned but if it's already interned (in the constant pool) then it returns the reference in the constant pool?

            – Hearen
            Mar 13 at 7:06













            @Hearen that's true, as the javadoc says - "When the intern method is invoked, if the pool already contains a string equal to this String object as determined bythe equals(Object) 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. "

            – Eran
            Mar 13 at 7:08





            @Hearen that's true, as the javadoc says - "When the intern method is invoked, if the pool already contains a string equal to this String object as determined bythe equals(Object) 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. "

            – Eran
            Mar 13 at 7:08













            sorry to disrupt you again. If that's so then why the second why still returns a true? ... so confusing now... but when I replaced the new StringBuilder().toString() with new String() both of them will become false. So weird...

            – Hearen
            Mar 13 at 7:13







            sorry to disrupt you again. If that's so then why the second why still returns a true? ... so confusing now... but when I replaced the new StringBuilder().toString() with new String() both of them will become false. So weird...

            – Hearen
            Mar 13 at 7:13






            2




            2





            "any list of pre-interned Strings" would depend on which JDK classes your program happened to load as well.

            – Alexey Romanov
            Mar 13 at 8:13





            "any list of pre-interned Strings" would depend on which JDK classes your program happened to load as well.

            – Alexey Romanov
            Mar 13 at 8:13




            2




            2





            @AlexeyRomanov and the launcher, e.g. the commonly used standard launcher loads the specfied main class and does a getMethod("main", String[].class) on it, thus “pre-interning” the string "main". A different launcher, e.g. a native launcher invoking the main method via JNI would behave differently. Likewise, the way command line options are processed may differ and hence, have different effect on the list of “pre-interned” strings.

            – Holger
            Mar 13 at 8:51







            @AlexeyRomanov and the launcher, e.g. the commonly used standard launcher loads the specfied main class and does a getMethod("main", String[].class) on it, thus “pre-interning” the string "main". A different launcher, e.g. a native launcher invoking the main method via JNI would behave differently. Likewise, the way command line options are processed may differ and hence, have different effect on the list of “pre-interned” strings.

            – Holger
            Mar 13 at 8:51















            3














            When the intern() method is invoked on a String object it looks the string contained by this String object in the pool, if the string is found there 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.



            So java string must already be in the pool. hence it is giving false.



            You can print all strings in pool



            How to print the whole String pool?



            Here is an example to get all string if you are using openjdk.






            share|improve this answer


























            • I just tried with the example in github you enclosed, it seems not working though I added the dependency it requires $JAVA_HOME/lib/sa-jdi.jar. As for the OS link, How to print the whole String pool?, it's not tested yet but looks so tricky. Thanks for the help :)

              – Hearen
              Mar 13 at 10:53


















            3














            When the intern() method is invoked on a String object it looks the string contained by this String object in the pool, if the string is found there 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.



            So java string must already be in the pool. hence it is giving false.



            You can print all strings in pool



            How to print the whole String pool?



            Here is an example to get all string if you are using openjdk.






            share|improve this answer


























            • I just tried with the example in github you enclosed, it seems not working though I added the dependency it requires $JAVA_HOME/lib/sa-jdi.jar. As for the OS link, How to print the whole String pool?, it's not tested yet but looks so tricky. Thanks for the help :)

              – Hearen
              Mar 13 at 10:53
















            3












            3








            3







            When the intern() method is invoked on a String object it looks the string contained by this String object in the pool, if the string is found there 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.



            So java string must already be in the pool. hence it is giving false.



            You can print all strings in pool



            How to print the whole String pool?



            Here is an example to get all string if you are using openjdk.






            share|improve this answer















            When the intern() method is invoked on a String object it looks the string contained by this String object in the pool, if the string is found there 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.



            So java string must already be in the pool. hence it is giving false.



            You can print all strings in pool



            How to print the whole String pool?



            Here is an example to get all string if you are using openjdk.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 13 at 10:41









            Hearen

            2,7841428




            2,7841428










            answered Mar 13 at 7:01









            SunnySunny

            9,12764680




            9,12764680













            • I just tried with the example in github you enclosed, it seems not working though I added the dependency it requires $JAVA_HOME/lib/sa-jdi.jar. As for the OS link, How to print the whole String pool?, it's not tested yet but looks so tricky. Thanks for the help :)

              – Hearen
              Mar 13 at 10:53





















            • I just tried with the example in github you enclosed, it seems not working though I added the dependency it requires $JAVA_HOME/lib/sa-jdi.jar. As for the OS link, How to print the whole String pool?, it's not tested yet but looks so tricky. Thanks for the help :)

              – Hearen
              Mar 13 at 10:53



















            I just tried with the example in github you enclosed, it seems not working though I added the dependency it requires $JAVA_HOME/lib/sa-jdi.jar. As for the OS link, How to print the whole String pool?, it's not tested yet but looks so tricky. Thanks for the help :)

            – Hearen
            Mar 13 at 10:53







            I just tried with the example in github you enclosed, it seems not working though I added the dependency it requires $JAVA_HOME/lib/sa-jdi.jar. As for the OS link, How to print the whole String pool?, it's not tested yet but looks so tricky. Thanks for the help :)

            – Hearen
            Mar 13 at 10:53













            0














            String literals (those that are hardcoded like "a string") are already interned for you by the compiler. But those strings that are acquired programmatically are not, and will be interned only if you use .intern() method.



            Usually you don't intern strings manually, unless you know you will store in memory a large number of repeating strings, so you can save a lot of memory that way.



            That is explained here:
            What is Java String interning?






            share|improve this answer






























              0














              String literals (those that are hardcoded like "a string") are already interned for you by the compiler. But those strings that are acquired programmatically are not, and will be interned only if you use .intern() method.



              Usually you don't intern strings manually, unless you know you will store in memory a large number of repeating strings, so you can save a lot of memory that way.



              That is explained here:
              What is Java String interning?






              share|improve this answer




























                0












                0








                0







                String literals (those that are hardcoded like "a string") are already interned for you by the compiler. But those strings that are acquired programmatically are not, and will be interned only if you use .intern() method.



                Usually you don't intern strings manually, unless you know you will store in memory a large number of repeating strings, so you can save a lot of memory that way.



                That is explained here:
                What is Java String interning?






                share|improve this answer















                String literals (those that are hardcoded like "a string") are already interned for you by the compiler. But those strings that are acquired programmatically are not, and will be interned only if you use .intern() method.



                Usually you don't intern strings manually, unless you know you will store in memory a large number of repeating strings, so you can save a lot of memory that way.



                That is explained here:
                What is Java String interning?







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Mar 14 at 0:29









                Hearen

                2,7841428




                2,7841428










                answered Mar 13 at 7:05









                maslanmaslan

                1,176923




                1,176923






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55135968%2fthe-return-of-string-intern-explained%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Magento 2 - Add success message with knockout Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?Success / Error message on ajax request$.widget is not a function when loading a homepage after add custom jQuery on custom themeHow can bind jQuery to current document in Magento 2 When template load by ajaxRedirect page using plugin in Magento 2Magento 2 - Update quantity and totals of cart page without page reload?Magento 2: Quote data not loaded on knockout checkoutMagento 2 : I need to change add to cart success message after adding product into cart through pluginMagento 2.2.5 How to add additional products to cart from new checkout step?Magento 2 Add error/success message with knockoutCan't validate Post Code on checkout page

                    Fil:Tokke komm.svg

                    Where did Arya get these scars? Unicorn Meta Zoo #1: Why another podcast? Announcing the arrival of Valued Associate #679: Cesar Manara Favourite questions and answers from the 1st quarter of 2019Why did Arya refuse to end it?Has the pronunciation of Arya Stark's name changed?Has Arya forgiven people?Why did Arya Stark lose her vision?Why can Arya still use the faces?Has the Narrow Sea become narrower?Does Arya Stark know how to make poisons outside of the House of Black and White?Why did Nymeria leave Arya?Why did Arya not kill the Lannister soldiers she encountered in the Riverlands?What is the current canonical age of Sansa, Bran and Arya Stark?