Language Fundamentals

Q1: What will be the output of the program?
public class CommandArgsTwo 
{
    public static void main(String [] argh) 
    {
        int x;
        x = argh.length;
        for (int y = 1; y <= x; y++) 
        {
            System.out.print(' ' + argh[y]);
        }
    }
}
and the command-line invocation is > java CommandArgsTwo 1 2 3

A 0 1 2

B 1 2 3

C 0 0 0

D An exception is thrown at runtime

ANS:A - 0 1 2

An exception is thrown because at some point in (System.out.print(' ' + argh[y]);), the value of x will be equal to y, resulting in an attempt to access an index out of bounds for the array. Remember that you can access only as far as length - 1, so loop logical tests should use x < someArray.length as opposed to x < = someArray.length.



img not found
img

For help Students Orientation
Mcqs Questions

One stop destination for examination, preparation, recruitment, and more. Specially designed online test to solve all your preparation worries. Go wherever you want to and practice whenever you want, using the online test platform.