Question about heap memory in Java

Question:

There was a question about heap memory . So pay attention to the bold italics. in the 1st option, everything works fine. But in the second one pops up

OutOfMemoryError: Java heap space.

Who can tell you why?

public class idea_test {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader("S:\\idea test\\src\\file.txt")); 
        ArrayList strings = new ArrayList();  

        (1)          
        String s;                                           
        while ((s = reader.readLine()) != null){
            strings.add(s);                                                     
        }

        (2)
        String s = reader.readLine();                                           
        while (s != null){
            strings.add(s);                                                     
        }

        reader.close();                                                         
        String[] strings1 = strings.toArray(new String[strings.size()]);        
        Arrays.sort(strings1);                                                  
        for (String s1 : strings1) {
            System.out.println(s1);
        }
    }
}

Answer:

In the first case, we are spinning in a loop and at each iteration we call

reader.readLine()

after which we check s for null , if all the lines of the file have been read ( (s = reader.readLine()) != null == false ), then we safely fall out of the loop.

In the second case, we get an infinite loop, since we once called

reader.readLine()

and then endlessly spinning in a loop (since s != null is always true, because we don't change s ), adding the same values ​​to ArrayList , which leads to OutOfMemoryError

Scroll to Top