12
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?

JJJ
  • 32,902
  • 20
  • 89
  • 102
Rahul Dev
  • 602
  • 1
  • 6
  • 16

1 Answers1

18

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
    }
    ....
}
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Exactly, nothing seems to be documented. which is why I was confused. – Rahul Dev Nov 19 '18 at 07:43
  • @RahulDev why would you be? In truth, even if it did create new object it does not mean that x == y would return false – Andrii Plotnikov Nov 19 '18 at 08:03
  • 4
    @Sarief if it created a new object (and returned that new object) `x == y` would definitely return false. – Eran Nov 19 '18 at 08:06
  • 2
    @Sarief it somehow got to [this list](https://stackexchange.com/questions?tab=hot), which tends to result in high traffic. – Eran Nov 19 '18 at 08:08
  • 1
    @Eran Let me rephrase, even if it had in contract that it creates a new object and it did create a new object, it does not mean that it will return a new object. Strings are contained in Strings pool and are reused mostly from there – Andrii Plotnikov Nov 19 '18 at 08:09
  • @Sarief why would it create a new object only to return a different (existing) object? That would be a waste of resources. – Eran Nov 19 '18 at 08:10
  • 1
    @Sarief First of all its not silly question, as Strings are immutable so any operation performed is expected to result in a separate object. Secondly the answer as many would think is related to same string in string pool, but its not as OP has created string using `new` and not invoked `intern()` hence correctly the answer points the implementation bwing the result as why no new object was created for the case presented by the question – nits.kk Nov 19 '18 at 08:12
  • @Eran I was talking about a very specific corner case. In that corner case the String has to be interned – Andrii Plotnikov Nov 19 '18 at 08:14
  • Also for all cases its always true if we have two references referring to two Different objects then `==` would always return fase, only `equals()` may result true based on the overridden behavior. – nits.kk Nov 19 '18 at 08:16
  • @nits.kk I guess it's different for me and for you, since I normally expect no operation to be performed when there is no difference and returning same object seems "obvious". It might not be so for everyone, as appears – Andrii Plotnikov Nov 19 '18 at 08:17
  • Hmm, there are instances such as one may have a method somewhat called as `copyObject` where you pass an existing object to return a copy of the same but want two different path of executions to use the object, mutate them differently later. here same states but you need two different objects. – nits.kk Nov 19 '18 at 08:21
  • 2
    @nits.kk this should not apply for immutable objects, which Strings are – Andrii Plotnikov Nov 19 '18 at 08:23