0

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.

harpun
  • 4,022
  • 1
  • 36
  • 40

2 Answers2

0

I think it's because return returnNumber; is computed before the finally block. At that point, returnNumber is 6. Then the finally block is executed, and returnNumber is incremented to 7, but by that time it's too late--testFinally has already decided that it's going to return 6.

ajb
  • 31,309
  • 3
  • 58
  • 84
  • This doesn't answer the question, just outlines the observations (poorly, because no comparison is made with the string builder) – Joost Oct 14 '13 at 19:21
0

If finally is executed everytime, then why is testFinally 6?

The increment is happening, but it's happening after you've returned a primitive value. What you've returned isn't an object.

Jon Lin
  • 142,182
  • 29
  • 220
  • 220
  • I don't think this is as much to do with primitives as it is to do with reassignment. The compound operator does `x = x + y`, so if you have returned `x` already then no-one will see the reassignment. The same would be true for an `Object`. – Boris the Spider Oct 14 '13 at 19:24