Java Five programs to generate stack overflow Exception and simple programs to generate stackoverflow Exception
Program-1 : Accessing a Null Object’s Method
java public class NullPointerExample1 { public static void main(String[] args) { String str = null; // Step 1: Declare a String variable and initialize it to null. System.out.println(str.length()); // Step 2: Attempt to call the length() method on the null object. } }
Explanation:
Step 1: The variable `str` is declared and set to `null`, meaning it does not point to any object.
Step 2: When `str.length()` is called, Java tries to access the method of a non-existent object, resulting in a `NullPointerException`.
Program-2: Accessing a Null Array Element
java public class NullPointerExample2 { public static void main(String[] args) { String[] array = null; // Step 1: Declare an array variable and initialize it to null. System.out.println(array[0]); // Step 2: Attempt to access the first element of the null array. } }
Explanation:
– Step 1: The variable `array` is declared as a null reference.
– Step 2: Trying to access `array[0]` results in a `NullPointerException` because the array itself does not exist.
Program-3: Modifying a Null Object’s Field
java public class NullPointerExample3 { public static void main(String[] args) { Person person = null; // Step 1: Declare a Person object and initialize it to null. System.out.println(person.name); // Step 2: Attempt to access the 'name' field of the null object. } static class Person { String name = "John Doe"; // Step 3: Define a Person class with a 'name' field. } }
Explanation:
Step 1: The `person` variable is initialized to `null`.
Step 2: Accessing `person.name` triggers a `NullPointerException` since `person` does not point to an actual `Person` object.
Step 3: The `Person` class itself is defined, but it is irrelevant since `person` is null.
Program-4: Calling a Method on a Null Object
java public class NullPointerExample4 { public static void main(String[] args) { Object obj = null; // Step 1: Declare an Object variable and initialize it to null. obj.toString(); // Step 2: Attempt to call the toString() method on the null object. } }
Explanation:
– Step 1: The variable `obj` is declared as null.
– Step 2: Calling `obj.toString()` causes a `NullPointerException` because there is no object to invoke the method on.
Program-5: Using a Null Value in a Collection
java import java.util.ArrayList; import java.util.List; public class NullPointer_Example5 { public static void main(String[] args) { List<String> list = new ArrayList<>(); // Step 1: Create an ArrayList of Strings. list.add(null); // Step 2: Add a null value to the list. System.out.println(list.get(0).length()); // Step 3: Attempt to call length() on the null element. } }
Explanation
Creating a program that generates a stack overflow in Java typically involves writing recursive functions that do not have a proper base case, leading to infinite recursion. Below are five different approaches to achieve this, each explained step by step.
Program-1: Simple Recursive Function
java public class StackOverflowExample1 { public static void recursiveMethod() { // Call itself indefinitely recursiveMethod(); } public static void main(String[] args) { recursiveMethod(); // Start the recursive calls } }
Explanation:
1. Function Definition: `recursiveMethod` calls itself without any termination condition.
2. Main Method: The program execution starts in the `main` method, where `recursiveMethod` is invoked.
3. Stack Overflow: Each call to `recursiveMethod` adds a new frame to the call stack, eventually exhausting memory and causing a `StackOverflowError`.
Program-2: Counting Recursion Depth
java public class StackOverflowExample2 { static int count = 0; public static void recursiveMethod() { count++; System.out.println("Count: " + count); recursiveMethod(); // Indefinite call } public static void main(String[] args) { try { recursiveMethod(); // Start the recursive calls } catch (StackOverflowError e) { System.out.println("Stack overflow occurred after " + count + " calls."); } } }
Explanation:
1. Static Counter: A static variable `count` tracks the number of recursive calls.
2. Printing Count: Each time the method is called, the current count is printed.
3. Error Handling: A `try-catch` block catches the `StackOverflowError`, allowing the program to report how many times it was able to call before failing.
Program-3: Recursive Method with Parameters
java public class StackOverflowExample3 { public static void recursiveMethod(int num) { // Call itself with incremented value recursiveMethod(num + 1); } public static void main(String[] args) { recursiveMethod(0); // Start recursion with initial value } }
Explanation:
1. Parameter Increment: The method takes an integer parameter and increments it with each call.
2. Indefinite Recursion: No base case exists to stop recursion, leading to stack overflow.
3. Main Method: Initiates the recursion with a starting value.
Program-4: Using an Array
java public class StackOverflowExample4 { static int[] largeArray = new int[Integer.MAX_VALUE]; // Large array to fill the stack public static void recursiveMethod(int index) { // Fill the array while calling itself largeArray[index] = index; recursiveMethod(index + 1); // Indefinite call } public static void main(String[] args) { try { recursiveMethod(0); // Start recursion with an initial index } catch (StackOverflowError e) { System.out.println("Stack overflow occurred!"); } } }
Explanation:
1. Large Array: An array of maximum size is created.
2. Recursion: The method fills the array and calls itself, leading to deep recursion.
3. Stack Overflow: The size of the stack is exceeded due to the large number of calls.
Program-5: Recursive Fibonacci Without Base Case
java public class StackOverflowExample5 { public static int fibonacci(int n) { return fibonacci(n - 1) + fibonacci(n - 2); } public static void main(String args[]) { try { System.out.println(fibonacci(10)); } catch (StackOverflowError e) { System.out.println("Stack-overflow-occur"); } } }
Explanation:
1. Fibonacci Calculation: The method computes Fibonacci numbers recursively.
2. Missing Base Case: Without a base case, it continues to call itself indefinitely.
3. Error Handling: The recursion will eventually lead to a `StackOverflowError`, which is caught in the `main` method.
One thought on “Java Five programs to generate stack overflow Exception.”