Excerpt from the answer to a similar question ...
Parameters and local variables are allocated on the stack (with reference types, the object lives on the heap, and the variable refers to this object). The stack is usually located at the upper end of your address space, and since it is used, it goes to the bottom of the address space (i.e., to zero).
There is also a bunch in your process that lives at the bottom of your process. When you allocate memory, this heap can grow at the upper end of your address space. As you can see, there is a possibility that the heap will βcollideβ with the glass (a bit like tectonic plates !!!).
The error means that the stack (your method) is full (executed so many times that it crashed). Errors usually occur due to a bad recursive call.
In general, if your method name does not contain the void keyword, make sure that the return value does not match the method name. Otherwise, the stack will overflow, breaking your program. Just replace these lines:
Math.sin(x); return sin(x);
... with this line ...
return Math.sin(x);
... and you should be good to go!
Sometimes it is difficult to determine when a program crashes:
Q: Will this program work? If so, why?
public void MultiplyByNintyNine(byte num) { MultiplyByNintyNine(num * 99); }
A: Actually, this can happen for two reasons:
The number can become so large that the JVM cannot process it.
A function can call itself so many times that the JVM crashes (i.e., an error).
The latter case is more reasonable; even though the method is not actually return , the method is still called.
In some cases, this is normal. return method name. Just make sure you have a termination condition if you do! Here is an example similar to yours (which doesn't crash):
import java.io.*; //class declaration here public static void main(String[] args) { System.out.println(guessTheNumber()); } public String guessTheNumber() { int guess; System.out.print("Guess the number:_"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { guess = Integer.parseInt(br.readLine()); } catch (NumberFormatException e) { System.err.println("You didn't guess a number."); guessTheNumber(); } catch (IOException e) { System.err.println("An unexpected error occured. Please try again."); guessTheNumber(); } if (guess == 4) { return "YAY! You get a prize!"; } else { System.err.println("WAAHH! You get to guess again!"); guessTheNumber(); } }
Warning: The only way to stop this code (from the code itself) is to enter 4 .
In the above case, the termination condition occurs when the user enters the actual number and this number is 4.
PS If you feel depressed, here is the REAL StackOverFlow Error!