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
There are a few reasons why developers use this pattern, even though your analysis of the runtime behavior and its use the string pool is correct.
As for your follow on questions:
Because the string pool is only used for string literals, as described by the JLS and invoking a constructor is not classified as a string literal.
The string pool is only used for string literals, but there is of course other caches for different use cases. The most obvious one that jumps to mind is the int cache used to optimize auto boxing of ints.
Even if the static doesn't give you a memory benefit in this case, you can still access the field in a static way, so you don't need an instance. For example, you frequently use some URIs, so you create the following class:
public class Uris
{
public static final String GOOGLE = "http://google.com";
public static final String BBC = "http://bbc.co.uk";
}
Using static, you can just use Uris.GOOGLE instead of new Uris().GOOGLE.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With