TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to JAVA

Java StackOverflowError

Analyze the StackOverflowError and see a solution for recursive methods.
StackOverflowError. As a method is called, it occupies a frame on the stack—an activation record. In a recursive method, many methods can be called, deeper and deeper.
At some depth, this causes an error—a StackOverflowError. The program will terminate. And we will be left with a confusing message.
An example. This program provokes a java.lang.StackOverflowError. It never terminates. The output is truncated in this example—many more x() calls are reported.

Note: This program is hopeless in its current form. With a count argument, though, we can prevent excess recursion.

Java program that causes StackOverflowError public class Program { public static void x() { // This recurses infinitely. x(); } public static void main(String[] args) { // Call the x method the first time. x(); } } Output Exception in thread "main" java.lang.StackOverflowError at Program.x(Program.java:5) at Program.x(Program.java:5) at Program.x(Program.java:5) at Program.x(Program.java:5) ...
Check depth. Here we introduce a count argument (an int) to our x() method. We add one to count on each nested call to "x." This restricts the depth of recursion.

Tip: This program will only ever have a recursion depth of 11 (it starts at 0 and continues until 10).

Java program that checks recursion depth public class Program { public static void x(int count) { // Check the count argument to prevent StackOverflowError. if (count >= 10) { return; } x(count + 1); } public static void main(String[] args) { // Begin. x(0); System.out.println("Done"); } } Output Done
With StackOverflowError, we have a descriptive error. Our program has a stack depth that is too great. We can restrict stack depth in certain recursive methods with an argument.Exceptions
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf