Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 848
Rahul Dev Avatar asked Nov 19 '18 07:11

Rahul Dev


People also ask

What does the toUpperCase () method do?

Description. The toUpperCase() method returns the value of the string converted to uppercase. This method does not affect the value of the string itself since JavaScript strings are immutable.

Does toUpperCase return a new string?

The “toUpperCase()” method is used for converting “string” characters to “uppercase” format. As JavaScript “string” is of “immutable” type, the “toUpperCase()” method returns a new string and does not modify the original string.

What is toUpperCase () an example of in JavaScript?

Javascript toUpperCase() is a built-in string function that converts a string to uppercase letters. The toUpperCase() method returns the calling string value converted to uppercase. To convert a string to uppercase in JavaScript, use the toUpperCase() method.

What does character toUpperCase do in Java?

The java. lang. Character. toUpperCase(char ch) converts the character argument to uppercase using case mapping information from the UnicodeData file.


1 Answers

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
    }
    ....
}
like image 94
Eran Avatar answered Oct 19 '22 19:10

Eran