| Author |
What's going on here?
|
jeff mutonho
Ranch Hand
Joined: Apr 30, 2003
Posts: 271
|
|
This code outputs 1.How does this happen? public class Puzzle1 { public int test() { int i = 0; try { //line 1 i++; //line 2 return i; //line 3 } finally { //line 4 i--; //line 5 } } public static void main(String[] args) { Puzzle1 p = new Puzzle1(); System.out.println(p.test()); } } jeff mutonho
|
 |
Ana Abrantes
Ranch Hand
Joined: Sep 04, 2003
Posts: 43
|
|
The code in the finally block is always executed. In this case, the value of i is returned then after that i is decremented though making no difference for the result of the method.
|
Ana<p>SCJP 1.4
|
 |
sanjana narayanan
Ranch Hand
Joined: Nov 25, 2003
Posts: 142
|
|
Hi, This is because of the return statement. I have made a simple modification to your code so that it returns 0(the return stmt is in the finally block) public class Puzzle1 { public int test() { int i = 0; try { //line 1 i++; //line 2 } finally { //line 4 i--; //line 5 return i; //line 3 } } public static void main(String[] args) { Puzzle1 p = new Puzzle1(); System.out.println(p.test()); } Hope it is clear.. Can u tell me the source for this question? -Sanjana
|
 |
jeff mutonho
Ranch Hand
Joined: Apr 30, 2003
Posts: 271
|
|
Got it from Dr Heinz Kabutz's newletter(www.javaspecialist.co.za). Ok , I knew the stuff you've told me , that no matter what , code in the finally block always gets executed.I ran the debugger on the code , with a break point set at line 1. When we reach line 1 the expected happens.i is incremented , then we hit the return statement , but immediately jump to line 4 to execute the finally block,where i is decremented back to 0(line5).But then , after that , there is a jump back to line 1 , then line 2 is skipped and then line 3 is executed(return), and the value 1 is finally printed out.
|
 |
 |
|
|
subject: What's going on here?
|
|
|