Menu
Question Index
...

Compare the following programs?

class ArrayOutput1
{
    public static void main(String s[])
    {
        int[][] input = {{3, 5, 6, 7}, {2, 4}, {1}, {2, 3, 4, 5}};
        int  result = 1;
        int k = 0;
        
        for(int i = 0; i < input.length; i++)
        {
            for(int j = 0; j < input[k].length; j++)
            {
                result *= input[i][j];
                k++;
            }
        }
        System.out.println("Result = " + result);
    }
}

class ArrayOutput2
{
    public static void main(String s[])
    {
        int[][] input = {{3, 5, 6, 7}, {2, 4}, {1}, {2, 3, 4, 5}};
        int  result = 1;
        int k = 0;
        
        for(int i = 0; i < input.length; i++)
        {
            for(int j = 0; j < input[k].length; j++)
            {
                result *= input[i][j];
            }
            k++;
        }
        System.out.println("Result = " + result);
    }
}


Both ArrayOutput1 and ArrayOutput2 produce same output.
ArrayOutput2 throws ArrayIndexOutOfBoundsException,
but ArrayOutput1 will compile and run with out any exception.
ArrayOutput1 throws ArrayIndexOutOfBoundsException,
but ArrayOutput2 will compile and run with out any exception.
Both ArrayOutput1 and ArrayOutput2 compile,
but they produce different output.
Both programs will throw ArrayIndexOutOfBoundsException.

Doubts

Problems

Topic: Learn Arrays And Loops

Read this topic
Take test on this topic

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App