So thanks to @fireshadow52, I’ve managed to come up with this script that sins args[0]. However, it spits out a StackOverFlow error. What is this, and how (if possible) would you spot them?
class SIN {
public static void main(String[] args) {
double result = sin(args[0]);
}
public double sin(x) { Math.sin(x); return sin(x); }
}
An excerpt from an answer to a similar question…
A Stack Overflow error means that the stack (your method) overflowed (executed itself so many times that it crashed). Stack Overflow errors usually result from a bad recursive call.
In general, if your method name doesn’t have the keyword
voidin it, make sure thereturnvalue isn’t the same as the method name. Otherwise, the stack will overflow, crashing your program. Just replace these lines:…with this line…
…and you should be good to go!
Sometimes in can be a bit tricky to find out when a program will crash:
Q: Will this program crash? If so, why?
A: Actually, this could crash for two reasons:
The number could get so large that the JVM can’t handle it.
The function could call itself so many times that the JVM crashes (i.e. a Stack Overflow error).
The latter case is the more reasonable; even though the method doesn’t actually
returnanything, the method is still called.In some cases, it is perfectly OK to
returnthe method name. Just make sure you have a terminating condition if you do, though! Here is an example similar to yours (that doesn’t crash):Warning: The only way to stop this code (from the code itself) is to enter
4.In the above case, the terminating condition occurs when a user enters an actual number and that number is 4.
P.S. If you’re feeling down, here is a REAL StackOverFlow error!