Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different output for 'run' and 'debug' when using readline()

Tags:

java

netbeans

I get two different output for the same code. I get one result when I debug and step through every line (using Netbeans 8.1). And I get a different result when I run the code all at once.

This is the code,

public class Testing {
    public static void main(String... args) throws IOException {
        BufferedReader file = new BufferedReader(new FileReader("input"));
        String str = file.readLine();
        System.out.println(str);
    }
}

This is the input file

first
second
third
fourth

The code should print the first line first in both cases. But it does that only when I run the code.

If I debug the code and step through every line, the second line second is printed.

Why is this happening?

Update: The following is a debugging screenshot. Right now, if I step over it will execute the System.out.println line. As you can see on the right side, str contains 'second'.

enter image description here

like image 603
Quazi Irfan Avatar asked Apr 01 '16 21:04

Quazi Irfan


1 Answers

Does your IDE evaluate file.readLine() while you are debugging? In Eclipse, one can define “watch expressions” that do exactly this.

This might explain your problem, since when you step through the code line by line, there is exactly one line in which file is defined and therefore the expression above can be evaluated. Therefore the output of second instead of first.

Update: Now that you added the screenshot, it’s clear. It’s partly the Netbean developer’s fault, since they chose “Variables” at the headline, which is misleading, since evaluating variables does not have a side-effect, while evaluating arbitrary expressions (like file.readLine()) clearly has.

like image 166
Roland Illig Avatar answered Nov 02 '22 20:11

Roland Illig