• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What's going on here?

 
jeff mutonho
Ranch Hand
Posts: 271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
sanjana narayanan
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic