Monday, 25 September 2017

Java Program for Bubble Sort in Ascending and Descending order

       Bubble sort is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements bubble to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort.

  Time Complexity:--

Best case performance    O(n)
Worst case performance  -  O(n^2)

Bubble Sort program for sorting in ascending order,

package com.pr;
public class BubbleSort {
 
      public static void main(String[] args) {
  
             BubbleSort sort = new BubbleSort();
             sort.bubbleSort(new int[]{1,10,4,3,8,2,15});
      }
 
      public void bubbleSort(int[] arr) {
             int length = arr.length;
  
             System.out.println("Array before bubble sort is: ");
             for (int i = 0; i< arr.length; i++) {
                    System.out.print(arr[i]+" ");
             }
  
             for (int i = 0; i<arr.length; i++) {
                  for (int j = 1; j< (length-i); j++) {
                        if (arr[j-1] > arr[j]) {
                             int temp = arr[j-1];
                             arr[j-1] = arr[j];
                             arr[j] = temp;
                        }
                  }
                  System.out.println("");
                  if (i== 0) {
                        System.out.println("Sorting step by step:");
                  }
                  for (int k = 0; k< arr.length; k++) {
                         System.out.print(arr[k]+" ");
                  }
             }
  
             System.out.println("");
             System.out.println("Array after bubble sort is: ");
             for (int i = 0; i< arr.length; i++) {
                    System.out.print(arr[i]+" ");
             }
      }
}
 

Output:-
Array before bubble sort is:
1 10 4 3 8 2 15
Sorting step by step:
1 4 3 8 2 10 15
1 3 4 2 8 10 15
1 3 2 4 8 10 15
1 2 3 4 8 10 15
1 2 3 4 8 10 15
1 2 3 4 8 10 15
1 2 3 4 8 10 15
Array after bubble sort is:
1 2 3 4 8 10 15


Bubble Sort program for sorting in descending order,

For descending order, change the above code at line no.15
arr[j-1] > arr[j] to arr[j-1] < arr[j],


package com.pr;
public class BubbleSort {
 
      public static void main(String[] args) {
  
             BubbleSort sort = new BubbleSort();
             sort.bubbleSort(new int[]{1,10,4,3,8,2,15});
      }
 
      public void bubbleSort(int[] arr) {
             int length = arr.length;
  
             System.out.println("Array before bubble sort is: ");
             for (int i = 0; i< arr.length; i++) {
                    System.out.print(arr[i]+" ");
             }
  
             for (int i = 0; i<arr.length; i++) {
                  for (int j = 1; j< (length-i); j++) {
                        if (arr[j-1] < arr[j]) {
                             int temp = arr[j-1];
                             arr[j-1] = arr[j];
                             arr[j] = temp;
                        }
                  }
                  System.out.println("");
                  if (i== 0) {
                        System.out.println("Sorting step by step:");
                  }
                  for (int k = 0; k< arr.length; k++) {
                         System.out.print(arr[k]+" ");
                  }
             }
  
             System.out.println("");
             System.out.println("Array after bubble sort is: ");
             for (int i = 0; i< arr.length; i++) {
                    System.out.print(arr[i]+" ");
             }
      }
}
 
Output: -
Array before bubble sort is:
1 10 4 3 8 2 15
Sorting step by step:
10 4 3 8 2 15 1
10 4 8 3 15 2 1
10 8 4 15 3 2 1
10 8 15 4 3 2 1
10 15 8 4 3 2 1
15 10 8 4 3 2 1
15 10 8 4 3 2 1
Array after bubble sort is:
15 10 8 4 3 2 1 

Sunday, 24 September 2017

Difference between the Runnable and Callable interface in Java

        This is also one of the important question of Java interview for middle level developer.  Runnable interface is added in JDK 1.0 where as Callable was added much later i.e in Java 5, along with many other concurrent features CopyOnWriteArrayList, ConcurrentHashMap, BlockingQueue and ExecutorService .
       
        If you see basic functionality both Callable and Runnable interfaces are implemented by any class whose instances are to be executed by another thread.  Callable interface have a some extra features which were not there in Runnable.  Those features are,
  • Callable can return value
  • It can throw exception 

Difference between Runnable and Callable:--


1)  The Callable and Runnable are interfaces and both have a single method but that method and it's signature is different.


Runnable:-

   public interface Runnable {
               public abstract void run();
     }

Callable :

   public interface Callable<V> { 
               V call() throws Exception;
     }


2)  Callable interface is a part of the java.util.concurrent package whereas Runnable interface is a part of the java.lang package.

3)  If you have noticed the signature of call method in the callable interface, you can see that call method can return value


      V call() throws Exception

  
     In the above code, V is the computed result.  Callable is a generic interface and type is provided at the time of creating an instance of Callable implementation.

Example:-

   Callable<Integer> callableObj = new    Callable<Integer>() {
          @Override
          public Integer call() throws Exception {
               return 2;
          }
    };

run() method of Runnable interface doesn't return any value,  return type is void. 

  @override
    public void run() {
         //does not return anything
    }
 
 
4)  Another difference that can be noticed from the signatures of the call() and run() method is that you can not give a exception with throws clause in run method.

  This below statement will give compile time error,

    public void run() throws InterruptedException
 
In call() method exception can be given with throws clause, as below.

    public Integer call() throws InterruptedException



5)  In order to run runnable task options are ,
  • Thread class has a constructor that takes Runnable as parameter.
  • Executor interface has execute method which takes Runnable as parameter.
  • ExecutorService has submit method which takes Runnable as parameter.
For Callable,
  • Thread class doesn't have any constructor that takes Callable as a parameter.
  • ExecutorService has submit method which takes Callable as a parameter.
  • ExecutorService also has invokeAll and invokeAny methods that takes Callable as a parameter.
  • Executors class has callable method that can convert Runnable to Callable 
    Callable callable = Executors.callable(Runnable task); 



Related Posts:-
1) How many ways to create a thread in Java? Which one Prefer and why?
2) Explain Thread life cycle and difference between wait() and sleep() method
3) Deadlock in Java multithreading - Program to generate the Deadlock and to avoid Deadlock in Java
4) Thread join() method example in Java
5) Producer Consumer Problem - Solution using wait and notify In Java

Saturday, 23 September 2017

Internal Implementation of LinkedList in Java

      In the previous post, we discussed the internal working of ArrayList. In this post, we will explore the internal working of LinkedList and understand the implementation of its main methods.

A LinkedList is a linear data structure in which each element is stored as a separate object called a node. Each node consists of two parts: the data and a reference to the next node in the list. The last node contains a reference to null, indicating the end of the list.

The entry point to a linked list is called the head. It is important to note that the head is not a separate node; rather, it is a reference to the first node in the list. If the list is empty, the head reference is null.


Linked List Node Structure


A linked list is a dynamic data structure. The number of nodes in a list is not fixed and can grow dynamically.

Types of LinkedList : --

1) Singly Linked List 
2) Doubly Linked List

       Below code is internal implementation or source code of add(), remove(), contains(), get() and size() methods of LinkedList(Singly Linked List).
 

package com.pr;
public class CustomLinkedList {
 
      private Node head;
      private int listcount;
 
      public CustomLinkedList(){
           head = new Node(null);
           listcount = 0;
      }
 
      public void add(Object data) {
           Node temp = new Node(data);
           Node current = head;
           while (current.getNext() != null) {
                current = current.getNext();
           }
           current.setNext(temp);
           listcount++;
       }
 
       public void add(Object data, int index) {
            Node temp = new Node(data);
            Node current = head;
            for (int i = 0; i < index && current.getNext() != null ; i++) {
                 current = current.getNext();
            }
            temp.setNext(current.getNext());
            current.setNext(temp);
            listcount++;
       }
 
       public Object get(int index) {
            if (index < 0) {
                 return null;
            }
            Node current = head.getNext();
            for (int i = 0; i<index; i++) {
                 if (current.getNext() == null)
                      return null;
                 current = current.getNext();
            }
            return current.getData();
      }
 
      public boolean remove(int index) {
          if(index < 0 && index > listcount) {
               return false;
          }
          Node current = head;
          for (int i = 0; i < index; i++) {
               if (current.getNext() == null)
                       return false;
               current = current.getNext();
           }
           current.setNext(current.getNext().getNext());
           listcount--;
           return true;
     }
 
     public boolean contains(Object obj) {
          Node current = head;
          for (int i = 0; i< listcount; i++) {
              if (current.getNext().getData().equals(obj))
                       return true;
                   current = current.getNext();
          }
          return false;
      }
 
      public boolean isEmpty() {
            return listcount == 0;
      }
 
      public int size() {
           return listcount;
      }
 }

class Node {
      Node next;
      Object data;
      public Node(Object data) {
           this.data = data;
           this.next = null;
      }
      public Node(Object data, Node next) {
           this.data = data;
           this.next = next;
      }
      public Node getNext() {
           return next;
      }
      public void setNext(Node next) {
           this.next = next;
      }
      public Object getData() {
           return data;
      }
      public void setData(Object data) {
           this.data = data;
      }
 }

The main program :--

package com.pr;

public class MainClass {
      public static void main(String[] args) {
            CustomLinkedList list = new CustomLinkedList();
            list.add("AB");
            list.add("BC");
            System.out.println(list.size());
            System.out.println(list.isEmpty());
            System.out.println(list.contains("AB"));
            System.out.println(list.get(1));  
      }
}

Output : - 2
                false

                true
                BC


Related Post : -   
1) Internal implementation of ArrayList in Java  
2) Collection Related Interview Questions and Answers in Java(List,Map & Set)  

Friday, 15 September 2017

What Are Generics in Java? Examples and Advantages of Using Generics

        Java 5 introduced an important feature called Java Generics. If you have worked with the Collections Framework in Java 5 or later versions, you have most likely used Generics.

At a high level, Generics are parameterized types that allow classes and methods to operate on objects of different types while providing compile-time type safety.

Generics add type safety to the Collections Framework and eliminate the need for explicit type casting. This helps detect errors during compile time itself. Fixing compile-time errors is generally easier than debugging runtime errors. It also helps prevent ClassCastException at runtime.

Let's understand this with an example. First, let's see how to create a List without using Generics:

   List list = new ArrayList(); 
   list.add(1); 
   list.add("A"); 
   Integer x = (Integer) list.get(1); //will throw ClassCastException at run time

In the above code, It will add any type of the Object into the list. It won't check the type safety hence there is no compile time error.  Only run time it can check for the type safety and will throw ClassCastException.

With Generics, same above code will be written as,

 
    List<Integer> list = new  ArrayList<Integer>(); 
    list.add(1); 
    list.add("A"); // It will show a compile time error.
    Integer x = list.get(0); 

The above code shows a compile-time error when attempting to add a String value to the list. This demonstrates type safety provided by Generics at compile time, as it does not allow adding elements of an incorrect type.

In this code, explicit type casting is not required while retrieving values from the list because the compiler already knows the type of elements stored in the collection.

Let us see another advantage of Generics: Type Inference.

Type inference is the ability of the Java compiler to determine the type arguments required for a generic method invocation by analyzing the method call and its context. The compiler examines the types of the arguments passed to the method and, if applicable, the type to which the result is assigned or returned. Based on this information, it determines the most specific type that satisfies all requirements.

Generic methods introduced the concept of type inference, which allows developers to invoke generic methods like normal methods without explicitly specifying the type arguments inside angle brackets (<>).


Generic Classes:-
 
The Generic class is an ordinary class with type parameters, example as below

public class GenericClass<T> {
     private T t;
 
     public void add(T t) {
          this.t = t;
     }
 
     public T get() {
          return t;
     }
 
     public static void main(String[] args) {

           GenericClass<String> stringClass = new GenericClass<String>();
           GenericClass<Integer> integerClass = new GenericClass<Integer>();
      
           stringClass.add(new String("Hello World"));
           integerClass.add(new Integer(1));
           System.out.println("Integer Value: " + integerClass.get());
           System.out.println("String Value: " + stringClass.get());
     }
}

Output:
Integer Value: 1
String Value: Hello World


Wildcards in Generics:-
  
In generic code, the question mark (?) is called a wildcard and represents an unknown type.

There are two types of wildcards in Generics:

  1. Bounded Wildcard

  2. Unbounded Wildcard

The bounded wildcard is further divided into two types:

  1. Upper Bounded Wildcard

  2. Lower Bounded Wildcard

Upper Bounded Wildcards

To declare an upper bounded wildcard, use the wildcard character (?) followed by the extends keyword and the upper bound type.

Note that, in this context, extends is used in a general sense to mean either extends (for classes) or implements (for interfaces).

An upper bounded wildcard restricts the unknown type to a specific type or a subtype of that type.

Consider the example below:

public static void sumOfList(List<? extends Number> list) {
   //some code
}
 
  Here, the argument list is bounded by the Number type. This method works with lists of Number and its subclasses, such as Integer, Double, and Float.

Lower Bounded Wildcards

To declare a lower bounded wildcard, use the wildcard character (?) followed by the super keyword and the lower bound type.

A lower bounded wildcard restricts the unknown type to be a specific type or a superclass of that type.

Consider the example below:


public static void sumOfList(List<? super Integer> list) {
   //some code

This method works on a lists of Integer or super type of Integer
 i.e lists of Number.


Unbounded Generics

An unbounded wildcard is specified using the wildcard character (?), for example, List<?>. It represents a list of an unknown type.

An unbounded wildcard is useful when writing a method that performs only read operations or uses only the common methods available in the Object class, without depending on any implementation-specific methods.

For example, you can write a common method that displays the elements of a list or calculates the size of a list, regardless of the type of elements stored in it.
  
public void display(List<?> list){
     Iterator<?> itr = list.iterator();
     while (itr.hasNext()) {
          System.out.println(itr.next());
     }
}
 
public static int sizeOfList(List<?> list){
      return list.size();
}

Type Erasure

Generics were introduced in Java to provide stronger type checking at compile time and to support generic programming.

Type erasure is the process by which the Java compiler removes generic type information during compilation. The compiler replaces type parameters with their bounded types, or with Object if the type parameters are unbounded. As a result, the generated bytecode contains only ordinary classes, interfaces, and methods.

The compiler also inserts type casts wherever required to maintain type safety.

Type erasure ensures that no new classes are created for parameterized types. Therefore, Generics do not introduce any runtime overhead.

Consider the below class:

 public class GenericClass<T> {
       private T t;
 
       public void add(T t) {
            this.t = t;
       }
 
       public T get() {
            return t;
       }
 }

Here T is an unbounded parameter so during type erasure process Java compiler replaces it with the Object. So the code after compilation is as follows,
 
  public class GenericClass {
       private Object t;
 
       public void add(Object t) {
            this.t = t;
       }
 
       public Object get() {
            return t;
       }
 }


Note : -  Standard convention to use Generic parameters are ,
         T -  Type parameter
         E -  Elements (using in LinkedList)
         K - Key in Map
         V - value in Map
         N - Number

Advantages of Spring JdbcTemplate Over the JDBC API

       Spring JdbcTemplate is a powerful mechanism to connect to the database and execute SQL queries. It internally uses JDBC API, but eliminate the lot of problems of JDBC API.

Problems While using JDBC API :- 

The common problems while using JDBC API are as below,

1) We need to write a lot of code before and after executing the query such as creating connection,
     statement and resultset and closing the resultset, statement and connection etc.

2) We need to perform exception handling code on the database logic.

3) We need to handle transaction.

4) Repetition of these codes i.e connection, statement and resultset codes for every transaction, so it's
    time consuming task.


Advantages of Spring JdbcTemplate : 

        Spring provides simplification in handling database access with the Spring JdbcTemplate which is in org.springframework.jdbc.core package.

  1) The Spring JdbcTemplate allows to clean-up the resources automatically, no need to write the
       extra code .

  2) The Spring JdbcTemplate converts the standard JDBC SqlExceptions into RuntimeExceptions.
      This allows the programmer to react more flexible to the errors.  And it also converts the vendor
      specific error messages to the better understandable error messages.

  3) The Spring JdbcTemplate offers several ways to query the database e.g queryForList() returns a
     list of HashMaps.  key is the column name of database and value is the actual column data.

  4) More convenient is the usage of ResultSetExtractor or RowMapper which allows to translates
       the SQL result direct into an Object or a list of Objects .


Example of JdbcTemplate :- 

Create one simple table employee, having id, name and salary are columns.
 
    create table employee(  
       id integer(10),  
       name character varying(100),  
       salary integer(10)  
    );  

The Employee class have properties id, name and salary with setters and getters. it's POJO class.
 
    package com.adnblog;  
      
    public class Employee {  
         private int id;  
         private String name;  
         private int salary;  
    //no-arg and parameterized constructors  
    //getters and setters  
    }  

The EmployeeDao class is having JdbcTemplate property and some methods having database operations.
 
package com.adnblog;  
import org.springframework.jdbc.core.JdbcTemplate;  
  
public class EmployeeDao {  
       
      private JdbcTemplate jdbcTemplate;  
  
      public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {  
            this.jdbcTemplate = jdbcTemplate;  
      }  
  
      public JdbcTemplate getJdbcTemplate() {
            return jdbcTemplate;
      }
      public int saveEmployee(int id, String name, int salary){  
            String query="INSERT INTO employee VALUES(?, ?, ?)";  
            return jdbcTemplate.update(query, id, salary);  
      }  
     
      public int updateEmployee(int id, String name, int salary){  
            String query="UPDATE employee
              SET name = ?, salary = ? WHERE id = ?";  
            return jdbcTemplate.update(query, name, salary, id);  
      }  

      public List<Employee> findAll(){

           String sql = "SELECT * FROM employee";

           List<Employee> employeeList = new ArrayList<Employee>();

           List<Map> rows = getJdbcTemplate().queryForList(sql);
           for (Map row : rows) {
               Employee emp = new Employee();
               emp.setId((Integer)(row.get("ID")));
               emp.setName((String)row.get("NAME"));
               emp.setSalary((Integer)row.get("SALARY"));
               employeeList.add(emp);
           }
           return employeeList;
     }
} 
 
        Another one interface ResultSetExtractor is interface used to fetch data from the database, it will take resultset data as input and will return in the form of list.  Another interface RowMapper you can read from google.


Related Posts:--
1) What are different Spring Bean Scopes?
2) Spring @Qualifier Annotation with example
3) Spring Configuration Metadata (XML, Annotation and Java)
4) What is IOC Container in Spring? Difference between BeanFactory and ApplicationContext
5) Spring Annotations

Friday, 8 September 2017

Java Program to Sort an ArrayList of Custom Objects by Properties Using the Comparator Interface

        In a previous post, we learned about the differences between the Comparable and Comparator interfaces. The Comparator interface is used to define custom sorting logic for objects.

In this post, we will learn how to sort an ArrayList of custom objects based on multiple properties using the Comparator interface.

Example: Sorting an ArrayList of Custom Objects by Multiple Properties

package com.pr;

import java.util.Comparator;
import java.util.Date;

public class ComparatorExample {

     public int id;
     public String name;
     public Date dof;
 
     public ComparatorExample(int id, String name, Date dof) {
            this.id = id;
            this.name = name;
            this.dof = dof;
     }
 
     public int getId() {
           return id;
     }
     public void setId(int id) {
          this.id = id;
     }
     public String getName() {
          return name;
     }
     public void setName(String name) {
          this.name = name;
     }
 
     public Date getDof() {
          return dof;
     }
     public void setDof(Date dof) {
          this.dof = dof;
     }

      //sorting based on Name, ascending order
     public static Comparator<ComparatorExample> nameComp = new Comparator<ComparatorExample> () {
  
            public int compare(ComparatorExample obj1, ComparatorExample obj2) {
                  return (obj1.getName().compareTo(obj2.getName())) ;
            }
     };
 
      //sorting based on id, ascending order
     public static Comparator<ComparatorExample> idComp = new Comparator<ComparatorExample> () {
  
            public int compare(ComparatorExample obj1, ComparatorExample obj2) {
                  if (obj1.getId() > obj2.getId()) {
                        return 1;
                  } else if(obj1.getId() < obj2.getId()) {
                        return -1;
                  } else {
                      return 0;
                  }
            }
      };
 
       // Sorting based on dof(i.e date format), ascending order
      public static Comparator<ComparatorExample> dofComp = new Comparator<ComparatorExample> () {
  
             public int compare(ComparatorExample obj1, ComparatorExample obj2) {
                   return obj1.getDof().compareTo(obj2.getDof());
             }
      };
 
      @Override
      public String toString() {
            return "Name :"+name +", id : "+id+", dof : "+dof;
      }
 }
 
The main class to execute this sorting is,
  

package com.pr;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;

public class MainClassComparator {
      public static void main(String[] args) throws ParseException {
  
            ArrayList<ComparatorExample> list = new ArrayList<ComparatorExample>();
            list.add(new ComparatorExample(60, "Kiran", 
                                  new SimpleDateFormat("yyyy-MM-dd").parse("1988-12-10")));

            list.add(new ComparatorExample(20, "Anand", 
                                   new SimpleDateFormat("yyyy-MM-dd").parse("1987-12-11")));

            list.add(new ComparatorExample(30, "Bharat", 
                                   new SimpleDateFormat("yyyy-MM-dd").parse("1988-12-09")));
  
            //Sorting based on id property
            Collections.sort(list, ComparatorExample.idComp);
            System.out.println("Sorting based on id property");
            for (ComparatorExample e : list) {
                 System.out.println(e);
           }
  
           //Sorting based on name property
            Collections.sort(list, ComparatorExample.nameComp);
            System.out.println("Sorting based on name property");
            for (ComparatorExample e : list) {
                 System.out.println(e);
            }
  
             //Sorting based on dof property
            Collections.sort(list, ComparatorExample.dofComp);
            System.out.println("Sorting based on dof property");
            for (ComparatorExample e : list) {
                 System.out.println(e);
            }
      }
}
OUTPUT
Sorting based on id property
Name :Anand, id : 20, dof : Fri Dec 11 00:00:00 GMT+05:30 1987
Name :Bharat, id : 30, dof : Fri Dec 09 00:00:00 GMT+05:30 1988
Name :Kiran, id : 60, dof : Sat Dec 10 00:00:00 GMT+05:30 1988
 
Sorting based on name property
Name :Anand, id : 20, dof : Fri Dec 11 00:00:00 GMT+05:30 1987
Name :Bharat, id : 30, dof : Fri Dec 09 00:00:00 GMT+05:30 1988
Name :Kiran, id : 60, dof : Sat Dec 10 00:00:00 GMT+05:30 1988
 
Sorting based on dof property
Name :Anand, id : 20, dof : Fri Dec 11 00:00:00 GMT+05:30 1987
Name :Bharat, id : 30, dof : Fri Dec 09 00:00:00 GMT+05:30 1988
Name :Kiran, id : 60, dof : Sat Dec 10 00:00:00 GMT+05:30 1988
 

Saturday, 2 September 2017

How to Generate StackOverflowError and OutOfMemoryError Programmatically in Java

    Every Java developer may encounter these types of errors while developing applications. In most cases, java.lang.OutOfMemoryError occurs because the JVM runs out of available memory, although memory leaks or inefficient code can also be contributing factors. If the issue is caused by insufficient heap memory, you can increase the JVM heap size using the -Xms and -Xmx options. (For example, the default maximum heap size in older Java versions such as Java 6 was relatively small.)

In this post, we will learn how to generate OutOfMemoryError and StackOverflowError programmatically.

OutOfMemoryError can occur for different reasons. In older Java versions (Java 7 and earlier), two common types were:

  • PermGen Space (java.lang.OutOfMemoryError: PermGen space)

  • Java Heap Space (java.lang.OutOfMemoryError: Java heap space)

A PermGen Space error could occur if the Permanent Generation became full, often due to excessive class loading or metadata retention. (Note: PermGen was removed in Java 8 and replaced with Metaspace.)

A Java Heap Space error occurs when the application creates more objects than the available heap memory can accommodate, and the garbage collector is unable to reclaim enough memory because many objects are still reachable.


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


 package com.pr;

 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;
                 System.out.println(a);
            }
       }

       public static void main(String[] args) {
              heapSpaceError error = new heapSpaceError();
              error.method();
       }
 }
 
Output : --
[I@eb42cbf
[I@56e5b723
[I@35a8767
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
 at com.pr.heapSpaceError.method(heapSpaceError.java:9)
 at com.pr.heapSpaceError.main(heapSpaceError.java:16)
 
 

java.lang.StackOverflowError  examples(Source code)

       
          The JVM stack is used to store local variables, primitive data types, object references, and method call information for each thread. When a method completes its execution, its stack frame is removed, and the memory occupied by the local variables is automatically released.

The JVM throws a java.lang.StackOverflowError when the stack memory is exhausted. This typically happens due to excessive or infinite recursive method calls, causing the stack to overflow.

The following example demonstrates how to generate a StackOverflowError programmatically using recursive method calls.


  package com.pr;

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

       public static void main(String[] args) {
             StackOverflowErrorEx ex = new StackOverflowErrorEx();
             ex.m(1);
       }
  } 
 
Output :--
Exception in thread "main" java.lang.StackOverflowError
 at com.pr.StackOverflowErrorEx.m(StackOverflowErrorEx.java:6)
 at com.pr.StackOverflowErrorEx.m(StackOverflowErrorEx.java:6) 



Related Post:-

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