• Post Reply Bookmark Topic Watch Topic
  • New Topic

can explain the output ?  RSS feed

 
Roshi Kumar
Greenhorn
Posts: 21
Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


why out is

finally
4


why not

finally
1
 
Paweł Baczyński
Bartender
Posts: 2076
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because you return a value equal to 4. Changing a variable that represented that value has no effect.
This is because primitive types are passed by value, not reference.
Consider this example:

Do you understand now?

If you wanted to change the result in finally clause you would need to do the following

 
Roshi Kumar
Greenhorn
Posts: 21
Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pawel Pawlowicz wrote:
Do you understand now?


not really .. here before passing result value , it's being changed to 1 in finally block then that valued is returned .. correct me if wrong ... SO output should be 1 ...

N thanks for replying

 
Paweł Baczyński
Bartender
Posts: 2076
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, I'll try another way.
you say
int result = 4;
and then
return result;

The program "thinks": I need to return the value of result. So I need to return 4.
This is because result was passed by value.
So now the program "remembers": I need to return 4. But wait, there is a finally block I need to run!
Notice that now the program "forgot" that the value 4 came from variable result. It only knows that 4 needs to be returned.
Now it prints "finally", changes result to 1 and then returns 4.

If you want to change the value it returns you need to call return again in the finally block as I showed you.
BTW, it's not a good idea to call that kind of overriding return from finally block. It leads to confusing code.
 
Tim Cooke
Marshal
Posts: 4039
239
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pawel Pawlowicz wrote:BTW, it's not a good idea to call that kind of overriding return from finally block. It leads to confusing code.


I would like to emphasise Pawel's point on this as it is very bad practice and will not gain you any friends in industry. If you presented this at a professional code review the "WTF rate" would be through the roof!

Don't do it. Just don't.
 
Roshi Kumar
Greenhorn
Posts: 21
Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!