When does the toUpperCase() method create a new object?

Rahul Dev :
public class Child{

    public static void main(String[] args){
        String x = new String("ABC");
        String y = x.toUpperCase();

        System.out.println(x == y);
    }
}

Output: true

So does toUpperCase() always create a new object?

Eran :

toUpperCase() calls toUpperCase(Locale.getDefault()), which creates a new String object only if it has to. If the input String is already in upper case, it returns the input String.

This seems to be an implementation detail, though. I didn't find it mentioned in the Javadoc.

Here's an implementation:

public String toUpperCase(Locale locale) {
    if (locale == null) {
        throw new NullPointerException();
    }

    int firstLower;
    final int len = value.length;

    /* Now check if there are any characters that need to be changed. */
    scan: {
        for (firstLower = 0 ; firstLower < len; ) {
            int c = (int)value[firstLower];
            int srcCount;
            if ((c >= Character.MIN_HIGH_SURROGATE)
                    && (c <= Character.MAX_HIGH_SURROGATE)) {
                c = codePointAt(firstLower);
                srcCount = Character.charCount(c);
            } else {
                srcCount = 1;
            }
            int upperCaseChar = Character.toUpperCaseEx(c);
            if ((upperCaseChar == Character.ERROR)
                    || (c != upperCaseChar)) {
                break scan;
            }
            firstLower += srcCount;
        }
        return this; // <-- the original String is returned
    }
    ....
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=36282&siteId=1