Why am I getting a stackoverflow error ?
My class -
public class Tester {
int id;
Tester(int id){
this.id = id;
}
public String toString(){
String rep = "Hex: " + this + ", Id: " + this.id;
return rep;
}
}
The main method -
class Driver{
public static void main(String [] args){
Tester t = new Tester(123);
System.out.println(t);
}
}
Error -
Exception in thread "main" java.lang.StackOverflowError
at java.lang.String.length(Unknown Source)
at java.lang.AbstractStringBuilder.append(Unknown Source)
at java.lang.StringBuilder.append(Unknown Source)
at java.lang.StringBuilder.<init>(Unknown Source)
at com.examscam.model.Tester.toString(Tester.java:13)
at java.lang.String.valueOf(Unknown Source)
at java.lang.StringBuilder.append(Unknown Source)
---------REPEAT !!!
StackOverflowError is a runtime error which points to serious problems that cannot be caught by an application. The java. lang. StackOverflowError indicates that the application stack is exhausted and is usually caused by deep or infinite recursion.
Solution. The simplest solution is to carefully inspect the stack trace and detect the repeating pattern of line numbers. These line numbers indicate the code that is being recursively called. Once you detect these lines, look for the terminating condition (base condition) for the recursive calls.
StackOverflowError is an error which Java doesn't allow to catch, for instance, stack running out of space, as it's one of the most common runtime errors one can encounter.
If your mobile device's operating system is giving you a stack overflow error, you may have too many applications running, a virus uses stack space, or your device has bad hardware. Check your app usage and virus protection and run a memory diagnostic app on your mobile device to see if this helps clear up your error.
Because
"Hex: " + this
is equivalent to
"Hex: " + this.toString()
and you're doing that from the toString()
, so toString()
calls itself, which calls itself, which calls itself...
You wrote:
String rep = "Hex: " + this + ", Id: " + this.id;
In java simply writing this
means that you are indirectly invoking this.toString()
.
I believe you are trying to override the toString()
method of Object
and inside your version of toString()
you want to print the id you have passed along with the hashcode
of the object.
So to get the output replace
String rep = "Hex: " + this + ", Id: " + this.id;
with
String rep = "Hex: "+ this.getClass().getName().hashCode() +", Id: " + id;
and you will get the output as:
Hex: 1800024669, Id: 123
you are using this
keyword.
String rep = "Hex: " + this + ", Id: " + this.id;
This represent the current object. Your current object is being called again and again recursivley so you are getting
java.lang.StackOverflowError
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With