Does the following code compile? If it does not, how can it be fixed? If it does
ID: 3738606 • Letter: D
Question
Does the following code compile? If it does not, how can it be fixed? If it does, what is it's output? Does it throw an exception? If so, how can it be fixed? public class Oops f static void foo (int[] a,int n) int i - a[n]; System. out.println("i-"+i) public static void main (String [] args) I try l try l foo (new int []12,3,6,4, -11,0); System.out.println("zero"); > catch (Exception e) foo (null,0); System. out .println("one"); J finally f System.out.println("two"); h System.out.println("three") System.out.println("four"); > > h - catch (Exception e2) 1 J finally f two three fourExplanation / Answer
It is very simple. the line(method ) foo(new int[]{2,3,6,4,-1},0) would be called inside the inner try block,
and then control goes the the static method foo( int a[], int a) where array a will have values
a[0]=2;
a[1]=3;
a[2]=6;
a[3]=4;
a[4]=-1
and n value is n=0.
Now int i=a[n]; where n=0, so i=a[0]=2 and then it prints i=2;
Now it again calls the same method foo( a,i) where now n value is equal to i which is 2
now i=a[n]; where n=2, so i=a[2]=6 and then it prints i=6
Again it calls foo(a,i) where i=6 but there are no 6 values in the array a, hence throw ArrayOutofBoundsException.
And the rest of the code is exceuted as expected.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.