Saturday, 2 September 2017

How to generate the StackOverflowError and OutOfMemoryError programmatically in Java

      Every Java Developer can face this type of error while developing application.  Mostly you will get the java.lang.OutOfMemoryError due to the system memory limitation rather than programming mistake. In this case,  you can increase the heap size of JVM by default it should be 256MB(Java 6).

      In this post, will discuss how to generate the OutOfMemoryError and StackOverflowError programmatically.  In OutOfMemoryError, again two types  PermGen space and heap space.
      If declared more String literals in application then it will throw PermGen Space error.  If you created so many Objects using new keyword and not garbage collected for unreferenced objects, it will throw heap space error because there is no sufficient memory to create the new objects.

java.lang.OutOfMemoryError : java heap space examples(Source code)


 public class heapSpaceError {
       public void method() {
            int value = 10;
            for (int i = 0; i<100; i++) {
                 int count = 5;
                 int[] a = new int[value];
                 value = value * 5;

       public static void main(String[] args) {
              heapSpaceError error = new heapSpaceError();
Output : --
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

java.lang.StackOverflowError  examples(Source code)

          The JVM stack is used to store primitive datatype, variables and method invocation and method calls.  If variables are removed, memory is freed for other variables at the end of the method execution. The JVM will throw java.lang.StackOverflowError if there is shortage of memory in the stack area.
       Below code is to generate the StackOverflowError programmatically,  by using the recursive calls. 


  public class StackOverflowErrorEx {
       public int m(int i) {
             return m(i++);

       public static void main(String[] args) {
             StackOverflowErrorEx ex = new StackOverflowErrorEx();
Output :--
Exception in thread "main" java.lang.StackOverflowError

Related Post:-

What is PermGen in Java? How to solve the Java.Lang.OutOfMemoryError: PermGen Space

1 comment:

  1. The information that you have shared is really useful for everyone. If someone wants to know about EHS Software and Occupational Safety Softwares I think this is the right place for you.