Rakesh Dagdi
Rakesh Dagdi

Reputation: 343

Error:Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

My program is as follows:

import java.util.*;

class evenNumber {
    ArrayList<Integer> arrL=new ArrayList<Integer>();

    ArrayList<Integer> saveEvenNumber(int N) {
        if(N<2)
            System.out.println("N should be greater than 2");
        else 
            for(int i=1;i<N;i++)
            {
                while(i%2==0)
                {
                    arrL.add(i);
                }
            }

        return arrL;
    }

    void printEvenNumber() {
        Iterator<Integer> tr=arrL.iterator();
        while(tr.hasNext())
            {
                System.out.print(tr.next());
                System.out.print("*2, ");
            }
    }
}


public class First {
    public static void main(String args[]) {
        evenNumber eN=new evenNumber();
        eN.saveEvenNumber(13);
        eN.printEvenNumber();
    }
}

I am getting the following error:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOf(Unknown Source)
    at java.util.Arrays.copyOf(Unknown Source)
    at java.util.ArrayList.grow(Unknown Source)
    at java.util.ArrayList.ensureCapacityInternal(Unknown Source)
    at java.util.ArrayList.add(Unknown Source)
    at list.evenNumber.saveEvenNumber(First.java:15)
    at list.First.main(First.java:35)`

I have changed the size in Run > Run configuration > Arguments as mentioned in other posts on the same error but then also I am getting the same error.

What should I do?

Upvotes: 2

Views: 3184

Answers (1)

Eugene
Eugene

Reputation: 11085

When i == 2, the while loop will be executed forever and that's the reason why java.lang.OutOfMemoryError is thrown.

Add a break; after arrL.add(i);.

As Thomas commented, use if statement is more suitable here.

BTW, refer to Naming Conventions for java naming. For your case, the first letter of class name should be capitalized. Use EvenNumber instead of evenNumber.

Upvotes: 6

Related Questions