I learned that String literals are not always garbage collected, so I wonder whether or not those two code examples are comparative in case of performance?
length() just returns the size of the internal character array of a String, so as long a String is not newly created, there is no computation needed.
// example 1
private static final int BAR_LENGTH = "bar".length();
public int foo() {
return BAR_LENGTH;
}
// example 2
public int foo() {
return "bar".length();
}