Reputation: 83
When I run this code I am getting a StackOverFlowError
at runtime. Why am I getting this Exception?
class F{
String name;
int rollNo;
F ref;
F(String name,int rollNo){
this.name = name;
this.rollNo = rollNo;
ref = this;
}
public static void main(String[] args){
F f = new F("Shivam",138);
System.out.println(f);
}
public String toString(){
return name+" "+rollNo+" "+ref;
}
}
This is the Exception I am getting:
Exception in thread "main" java.lang.StackOverflowError
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:449)
at java.lang.StringBuilder.append(StringBuilder.java:136)
at F.toString(F.java:20)
at java.lang.String.valueOf(String.java:2994)
at java.lang.StringBuilder.append(StringBuilder.java:131)
at F.toString(F.java:20)
at java.lang.String.valueOf(String.java:2994)
at java.lang.StringBuilder.append(StringBuilder.java:131)
at F.toString(F.java:20)
at java.lang.String.valueOf(String.java:2994)
Upvotes: 1
Views: 120
Reputation: 1274
Problem with overridden method toString() when you use ref it calling its toString() method and again same method call became recursive which causes the problem. You should use field of your class instead of same class object.
Upvotes: 1
Reputation: 1314
It's because you are self referencing using ref
and printing in toString()
which creates an endless recursion of toString()
being called. Not sure why you need a self reference in the first place, you can just use this
when needed. if you really need ref
, you can remove it from toString()
method and it should work.
Upvotes: 1
Reputation: 3232
System.out.println(f); // cause StackOverFlow Exception
when this line executes toString()
method called of f
object. and
see the implementation of toString()
public String toString(){
return name+" "+rollNo+" "+ref;
}
In which you again concatenate the ref
object so, toString
method recursively calling infinitely.
change implementation of toString
to this.
public String toString(){
return name+" "+rollNo;
}
Upvotes: 6