1

Here is the portion of the code which works weird while debugging

public static void main(String[] args) { //Line-1
    int a = 5; //Line-2
    System.out.println(++a); //Line-3
} //Line-4

When I run it in normal mode it gives output as 6 which is correct. But while debugging I kept a break point at Line-3 and first time when I inspected the value of ++a it showed 6 next time it was 7,8,9...

When I ended the program it showed output as 10 in the console. Why is that?

These solutions C++ - Eclipse behavior is different while debugging and running, How post Increment ++ Operator works while initialization didn't give any proper idea.

Arun Sudhakaran
  • 2,167
  • 4
  • 27
  • 52
  • 4
    The debugger, when evaluating the expression, is incrementing `a` over and over again on each evaluation. i.e. evaluating `++a` has side effects, and can not be done without affecting application state – Michael May 23 '19 at 09:58
  • @Michael that's right instead of inspecting `++a` if I inspect just `a` there won't be a change – Arun Sudhakaran May 23 '19 at 10:04

1 Answers1

2

When you evaluate the value of the expression ++a in debug mode, you really increment the variable. So it impacts the final result.

Vincent Passau
  • 814
  • 8
  • 22