Search code examples
javastringstring-comparison

Why the String returned by String.toLowerCase() is not interned?


I was asked to predict the output of this code :

String party1 = "party";
String party2= "PARTY".toLowerCase();
if(party1==party2){
   System.out.println("EQUAL");
}else{
   System.out.println("NOT EQUAL");
}

I thought the result of toLowerCase() would be interned automatically and hence the same reference to party1 would be returned, but I was wrong since the code ouptuts "NOT EQUAL".
Does toLowerCase() (toUpperCase() as well) return a new String ?

Edit : I am not using == to compare Strings, I just want to know about the behaviour of toLowerCase() method


Solution

  • If the result of any String operation were internalised, the pool would be growing extremely and unnecessarily rapidly. Any intermediate action on a Spring would result in a new element in the pool. It would be beneficial for a VERY small number of cases within a VERY specific domain. Therefore, it's not the default policy and that's why intern() exists.

    String party1 = "party";
    String party2 = "PARTY".toLowerCase().intern();
    System.out.println(party1 == party2 ? "EQUAL" : "NOT EQUAL");
    

    There is nothing special about toLowerCase(): any String method would return a new String since Strings are immutable.