Knowee
Questions
Features
Study Tools

What is the output of the following?class GFG{    public static void main (String[] args)    {        int[] arr = new int[2];        arr[0] = 10;        arr[1] = 20;          for (int i = 0; i <= arr.length; i++)            System.out.println(arr[i]);    }}

Question

What is the output of the following?class GFG{    public static void main (String[] args)    {        int[] arr = new int[2];        arr[0] = 10;        arr[1] = 20;          for (int i = 0; i <= arr.length; i++)            System.out.println(arr[i]);    }}

🧐 Not the exact question you are looking for?Go ask a question

Solution

The code you provided is written in Java. It's trying to print out the elements of an array. However, it will throw an ArrayIndexOutOfBoundsException.

Here's why:

  1. An array arr of size 2 is created.
  2. The first element of the array (at index 0) is set to 10.
  3. The second element of the array (at index 1) is set to 20.
  4. A for loop is set up to iterate from 0 to the length of the array. In Java, arrays are 0-indexed, meaning the first element is at index 0 and the last is at index length - 1. So, the loop should run from 0 to arr.length - 1.
  5. However, in your code, the loop is set to run from 0 to arr.length (i.e., 2), which means it will try to access arr[2] on the third iteration.
  6. Since arr[2] doesn't exist (the array only has elements at indices 0 and 1), the Java runtime will throw an ArrayIndexOutOfBoundsException.

To fix this, you should change the loop condition to i < arr.length instead of i <= arr.length. This will ensure the loop only runs for valid indices of the array.

This problem has been solved

Similar Questions

What is the output of the following code :class MyClass {public static void main(String[] args) {int i=1,j=1;for (;i<3;i++){for(;j<4;j++);j++;System.out.print(i + j+" ");}}

What is output of the following code:public class Test{ public static void main(String[] args){ int[] x = {120, 200, 016 }; for(int i = 0; i < x.length; i++) System.out.print(x[i] + " "); }

e correct answerWhat is the output of the following Java program?class Main { public static void main(String args[]) { final int i; i = 20; i = 30; System.out.println(i); }}

What's the output of the following code?public static void main(String[] args) { int[] vals = {4, 3, 2, 1}; for (int v : vals) { System.out.println(indexOf(vals, v)); }}public static int indexOf(int[] all, int element) { for (int i = 0; i < all.length; i++) { if (all[i] == element) return i; } return -1;}

public class Question { public static void main(String args[]) { int f = 0, g = 1; for(int i = 0; i <= 5; i++) { System.out.println(f); f = f + g; g = f - g; } }}

1/3

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.