looking for some solutions? You are welcome.

SOLVED: the return of String.intern() explained?

    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

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", "java" == new String("java"));
    assertFalse("new StringBuilder() should create a new instance",
            "java" == new StringBuilder("java").toString());

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 any way to get kind of a list of them? Just curious about what they can be.

Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots

No comments: