I have seen a couple of such tricky pieces of code while i prepare for a Java certification.
The return value at the end here is : 10, but finally is called and it modifies the returnval to 20.
Can someone explain why this is so ? is it because the catch has a different scope of the returnval ? or am i missing something here.
class MultipleReturn {
int getInt() {
int returnVal = 10;
try {
String[] students = {"Harry", "Paul"};
System.out.println(students[5]);
}
catch (Exception e) {
System.out.println("About to return :" + returnVal);
return returnVal;
}
finally {
returnVal += 10;
System.out.println("Return value is now :" + returnVal);
}
return returnVal;
}
public static void main(String args[]) {
MultipleReturn var = new MultipleReturn();
System.out.println("In Main:" + var.getInt());
}
}
Another follow up piece of code is :
class MultipleReturn {
StringBuilder getStringBuilder() {
StringBuilder returnVal = new StringBuilder("10");
try {
String[] students = {"Harry", "Paul"};
System.out.println(students[5]);
}
catch (Exception e) {
System.out.println("About to return :" + returnVal);
return returnVal;
}
finally {
returnVal.append("10");
System.out.println("Return value is now :" + returnVal);
}
return returnVal;
}
public static void main(String args[]) {
MultipleReturn var = new MultipleReturn();
System.out.println("In Main:" + var.getStringBuilder());
}
}
here the output is 1010 which makes sense as the finally modifies the returnval and it gets persisted.
Any explanation will be helpful.
i do understand this is poorly written code and nobody in the right mind should be writing anything like this.