1

In the below mentioned program, Contrasting output for string and primitive value. How is this internally working??

public class Test {

    public static void main(String[] args) {

        String s1 = String.valueOf(99);
        String s2 = String.valueOf(99);
        System.out.println(s1==s2); //returns false, why??

         s1 = String.valueOf("99");
     s2 = String.valueOf("99");
        System.out.println(s1==s2);  //returns true, why??


}
}   
kumar Anny
  • 346
  • 4
  • 12
  • @Jon I don't think this is really the appropriate dupe. I mean, sure, you don't compare string values like this; but that doesn't explain why the reference is the same in one case but not the other. – Andy Turner Jul 26 '16 at 12:38
  • @AndyTurner: You could be right. Reopening. – Jon Skeet Jul 26 '16 at 12:40
  • Exactly this is not the duplicate question. The output varies depending on choosing String or primitive type as parameter. – kumar Anny Jul 26 '16 at 12:40

1 Answers1

3

String.valueOf("99") returns the same instance passed to it (since valueOf(Object obj) returns that Object's totString and String's toString returns this). Since both "99" Strings are the same instance (due to String pool), both calls to String.valueOf("99") return the same instance.

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

/**
 * This object (which is already a string!) is itself returned.
 *
 * @return  the string itself.
 */
public String toString() {
    return this;
}

On the other hand, each call to String.valueOf(99) calls Integer.toString(99), which produces a new String instance.

public static String valueOf(int i) {
    return Integer.toString(i);
}

public static String toString(int i) {
    if (i == Integer.MIN_VALUE)
        return "-2147483648";
    int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
    char[] buf = new char[size];
    getChars(i, size, buf);
    return new String(buf, true);
}
Eran
  • 387,369
  • 54
  • 702
  • 768