Home > Back-end >  different result in debug and run mode in a simple Java program
different result in debug and run mode in a simple Java program

Time:08-01

I have to ask this confused question again. My simple program is listed below:

public class App {
    public static void main(String[] args){
        ListNode target = init(new int[]{1,2,3,4,5});
        System.out.println(target);
    }

    public static ListNode init(int[] value){
        ListNode tail = null;
        ListNode head = null;
        for(int i=value.length-1; i>=0; i--){
            head = new ListNode(value[i], tail);
            tail = head;
        }
        return head;
    } 
}


class ListNode {
    int val;
    ListNode next;
    public ListNode(int val, ListNode next) { this.val = val; this.next = next; }

    @Override
    public String toString() {
        String s = ""   val;
        while(this.next != null){
            s = s   this.next.val;
            this.next = this.next.next;
        }
        return s;
    }
}

I use JDK Temurin 17.0.4 When I use run in the IDE, it returns correctly. When I use debug without any break point, it returns correctly. But when I use debug with the break point, the result is not correct. My program is just as simple as this, without any multi-threads features. At the beginning, I thought it was the IDE behavior. But I tried in both VSCode and IDEA, got the same results. debug in vscodedebug in idea

Not sure if the information I provided is sufficient to raise a question in stackoverflow, if anything more I have to add, pls let me know, I will add anything I have, as long as this one won't be treated as simple and stupid question and was deleted as last time..:)

Any help will be appreciated. Thanks.

CodePudding user response:

You break your link within the ListNode toString since you change the nodes link, which will make it eventually be just null and only be able to fetch it's own value.

Introducing a variable to store the link will keep the original value.

class ListNode {
    int val;
    ListNode next;
    public ListNode(int val, ListNode next) { this.val = val; this.next = next; }

    @Override
    public String toString() {
        String s = ""   val;
        ListNode curr = this.next;
        while(curr != null){
            s = s   curr.val;
            curr = curr.next;
        }
        return s;
    }
}

CodePudding user response:

IDEA will call the toString() method when debugging, and will not enter the breakpoint.

enter image description here

  •  Tags:  
  • java
  • Related