2

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?

3
  • 4
    You keep adding elements to your list in while(i%2==0) { arrL.add(i); }. Independent of your memory settings, this will run out of memory sooner or later. Commented Jul 21, 2016 at 7:18
  • 2
    In addition to Andreas' comment I guess you want to use if(i%2==0) instead. Commented Jul 21, 2016 at 7:19
  • 1
    Your way of iterating in printEvenNumber is one way to do it, but a simple for loop would be more readable: for (Integer i : arrL) { System.out.print(i); System.out.print("*2, "); } would do the same. Commented Jul 21, 2016 at 7:34

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

An if-statement would be the better solution here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.