Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java debugging doesn't show current line correctly

I have a simple java class , and I set a break point at main method and step by clicking 'step into' (netbeans ide).

Expected:

green line goes to line 4 and 5 until loop ends

What happens:

It stays at line 4.

I can see in the console that the value of i get printed.
If i gets printed, that mean it should go to line 5 which is System.out.print(i+" > ");.

Why it stays at line 4 until loop ends ?

Here is the preview:

enter image description here

This is the code i'm debugging:

2 | public class NewClass2 {
3 |     public static void main(String[] args) {
4 |         for (int i = 0; i < 10; i++) {
5 |             System.out.print(i+" > ");
6 |         }
7 |         System.out.println("end of the loop");
8 |     }
9 | }
like image 270
while true Avatar asked Jul 28 '15 08:07

while true


1 Answers

I have seen similar behavior to this before while using IntelliJ. I believe what is happening is that the call to System.out.println() actually gets optimized during the build process. As a result, the call to System.out doesn't actually exist once you have finished building the code. And when you go to debug, the debugger cannot get a hook into this code because it is not really there in the form you see on the screen.

By the way, you should get a badge for posting a very nice animated GIF in your OP. I think this is the first time I have seen this, and it worked very nicely in your question.

If you want to "trick" the IDE into being able to "see" the System.out call, you can try using the following code:

public static void main(String[] args) {
    for (int i = 0; i < 10; i++) {
        String stuff = "";
        System.out.print(i + " > " + stuff);
        stuff += "more stuff";
    }
    System.out.println("end of the loop");
}

Add your breakpoint right on the line with System.out and your NetBeans IDE might be able to see it. I have tried something similar to this with IntelliJ with varying degrees of success.

like image 189
Tim Biegeleisen Avatar answered Sep 18 '22 00:09

Tim Biegeleisen