static final String = "something";
I was wondering if such a declaration has some kind real sense in Java. I've found it thousands of time within the code but studying and playing with strings I've learnt that does not matter how many times you declare a String
object: if some class before yours declared this string this is pooled and reused (I'm talking about String created without explicit constructor invocation)
public class StringCompare {
private void toCompare(String h) {
String x = "hello";
System.out.println( x == h);
}
public void compare() {
String h = "hello";
toCompare(h);
}
}
This code, in fact, prints true
when calling compare so the 2 variables are referencing the same object. Said that a final
variable can't be redefined, the static
word is completely useless in this case. Am I missing the point?
Couple of more things:
1 - Why explicit call to String
constructor won't cause the String to be pooled? Same code above using a new String("hello")
print false
.
2 - Is the pooling behaviour reserved to Strings? There are some other immutable objects (like BigInteger) but I think these are not pooled ... why?
Thanks, Carlo