I got a try catch finally java question. The code is like this:
package com.test;
public class TestExamples {
public int testFinally(int inputNum) {
int returnNumber = inputNum;
try {
returnNumber++;
return returnNumber;
} finally {
returnNumber++;
}
}
public StringBuilder testFinallyString() {
StringBuilder builder = new StringBuilder();
try {
builder.append("cool");
return builder.append("try");
} finally {
builder.append("finally");
}
}
public static void main(String[] args) {
TestExamples testExamples = new TestExamples();
System.out.println("The result of testFinally is " + testExamples.testFinally(5));
System.out.println("The test of testFinallyString is " + testExamples.testFinallyString());
}
}
The results:
The result of testFinally is 6
The test of testFinallyString is cooltryfinally
If finally is executed everytime, then why is testFinally 6? I am bit puzzled that finally code block doesnt result in incrementing the number that is returned. Pls can someone throw more light on what can be the underlying reason.