
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Out of Memory Exception in Java
Whenever you create an object in Java it is stored in the heap area of the JVM. If the JVM is not able to allocate memory for the newly created objects an exception named OutOfMemoryError is thrown.
This usually occurs when we are not closing objects for long time or, trying to act huge amount of data at once.
There are 3 types of errors in OutOfMemoryError −
- Java heap space.
- GC Overhead limit exceeded.
- Permgen space.
Example 1
public class SpaceErrorExample { public static void main(String args[]) throws Exception { Float[] array = new Float[10000 * 100000]; } }
Output
Runtime exception
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at sample.SpaceErrorExample.main(SpaceErrorExample.java:7)
Example 2
import java.util.ArrayList; import java.util.ListIterator; public class OutOfMemoryExample{ public static void main(String args[]) { //Instantiating an ArrayList object ArrayList<String> list = new ArrayList<String>(); //populating the ArrayList list.add("apples"); list.add("mangoes"); list.add("oranges"); //Getting the Iterator object of the ArrayList ListIterator<String> it = list.listIterator(); while(it.hasNext()) { it.add(""); } } }
Output
Runtime exception
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at sample.SpaceErrorExample.main(SpaceErrorExample.java:7)
Advertisements