Skip to content

Instantly share code, notes, and snippets.

@tamboer
Created December 16, 2017 11:45
Show Gist options
  • Select an option

  • Save tamboer/c60efae705d5051ec812a38aff5fde8a to your computer and use it in GitHub Desktop.

Select an option

Save tamboer/c60efae705d5051ec812a38aff5fde8a to your computer and use it in GitHub Desktop.
Java stack overflow - Stack and Heap

Stack and Heap

Recursion

The following code will generate an error

public class App {

	public static void main(String[] args) {
		int value = 4;
		calculate(value);
	}
	
	private static void calculate(int value)
	{
		value = value-1;
		System.out.println(value);
		calculate(value);
	}

}

Because in Java when you call a method from within another method there is special area in memory of JVM called stack. And stack is used for local variables and for rememebering which method called which method.

So, we know the value after the method returns something. That's distinct from heap where object are allocated in memory.

  • We got stack overflow error because we call the function infinitely.
  • Not recommened because of stack overflow error.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment