Question: ( Optional ) Consider the following Test.java file. / / inside main System.out.println ( foo ( Hello ) ) ; / / line 6 /

(Optional) Consider the following Test.java file.
// inside main
System.out.println (foo(Hello)); //line 6
// more line of codes
.....
.....
public static int foo (String s)//line 9
{
if (s.length()==0)
return 0;
else
return (1+ foo (s.substring(0, s.length()-2))); //line 15
}
The code compiles, but when it runs, you get the following output:
Exception in thread main java.lang.StringIndexOutOfBoundException: begin 0, end -1, length 1
at java.base/java.lang.String.checkBoundsBeginEnd(Unknown source)
at java.base/java.lang.String.subString(Unknown source)
at Test.foo(Test.java:15)
at test.foo(Test.java:15)
at Test.foo(Test.java:15)
at test.main(Test.java:6)
Explain what the problem is and how it happens.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!