What is the difference between
private static final String JDBC_URL = getURL();
and then defining the getURL()
like:
private static String getURL() {
return "jdbc:mysql://localhost:3306/";
}
with the following code:
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/";
I found that writing mock
test was easier with the above one. I might be wrong. Just wanted to know if both ways are same. Thanks.
The second way is a compile-time constant, so elsewhere in your code when you refer to the value, it won't actually refer to the field - it will just have the value baked in.
Unless you start messing with the field via reflection or something similarly nasty you shouldn't notice any semantic differences, but that will be a difference in the bytecode.
See more on this question at Stackoverflow