String guessWho(){
String toReturn = "Hello";
try {
return toReturn;
} finally {
return toReturn + " World";
}
}
Believe it or not, most probably believed, the returned value is the one in the finally clause ("Hello World"), well after all that's expected since the last executed line in the method would be the ones in the finally clause.
But...
String guessWho(){
String toReturn = "Hello";
try {
return toReturn;
} finally {
toReturn = toReturn + " World";
}
}
Returns "Hello" only!, it seems that it only takes into account what you do with the reference before the finally clause.
Now... The same thing does not happen if you change state in an object, for instance:
StringBuilder getFinallyResult() {
StringBuilder builder = new StringBuilder();
builder.append("Hello");
try {
return builder;
} finally {
builder.append(" World");
}
}
Returns "Hello World" so the assumption applies only for references, not state.
0 comments:
Post a Comment