77.0k views
0 votes
What is the output of the following code fragment:

int[] y = new int[5];
y[0] = 34;
y[1] = 88;
System.out.println( y[0] + " " + y[1] + " " + y[5] );

User Hari Kanna
by
8.4k points

1 Answer

1 vote

Final answer:

The code will cause a runtime error as it tries to access an array element outside its bounds. Without this error, it would output the values 34 and 88 for the first two initialized elements of the array.

Step-by-step explanation:

The output of the given code fragment in Java will result in a runtime error. This error occurs because the code attempts to access y[5], which is an index out of bounds of the array y (declared with a size of 5, thus having valid indices from 0 to 4). The correct way to access the last element of the array would be y[4]. If there was no attempt to access y[5], the output would simply be the values stored at y[0] and y[1], namely 34 and 88.

User Syed Ali Naqi
by
8.8k points