2

It's my first post and I know similar things were posted.... but i got a problem understanding something. I know the difference with ++i and i++

  1. ++i first increments the 'i' then return value of 'i'
  2. i++ increments 'i' and returns value before it was incremented

I got a question on Job interview: "What will be the value of i"

int test(){
   int i = 0;
   try {
    return i++; 
   } finally {
    return ++i;
   }
}

According to what i wrote above, i thought it should be 1. But after checking it in some test app i know its 2. So my Question is: Why?

When i played with it a little and switched ++i with i++

int test(){
   int i = 0;
   try {
    return ++i; 
   } finally {
    return i++;
   }
}

In this case value of i is as expected 1. So why is that?

Viktor Mellgren
  • 4,318
  • 3
  • 42
  • 75

1 Answers1

0

When the finally block, which always gets executed, contains a return statement, the method returns whatever the finally block returns.

Hence, in the first case, the return i++ in the try block increments i to 1 but doesn't return it, and the return ++i in the finally block increments i to 2 and returns that incremented value (since it's a pre-increment operator).

If you swap the operators, the return ++i in the try block increments i to 1 but doesn't return it, and the return i++ in the finally block increments i to 2 but returns the value prior to that increment - 1 (since it's a post-increment operator).

In other words, the returned value doesn't depend on whether the try block contains ++i or i++. It only depends on whether the finally block contains ++i or i++.

Eran
  • 387,369
  • 54
  • 702
  • 768