Exercise: Language Fundamentals

Questions for: Language Fundamentals

public class F0091 
{    
    public void main( String[] args ) 
    {  
        System.out.println( "Hello" + args[0] ); 
    } 
}

What will be the output of the program, if this code is executed with the command line:

> java F0091 world

A:
Hello
B:
Hello Foo91
C:
Hello world
D:
The code does not run.
Answer: D

Option D is correct. A runtime error will occur owning to the main method of the code fragment not being declared static:

Exception in thread "main" java.lang.NoSuchMethodError: main

The Java Language Specification clearly states: "The main method must be declared public, static, and void. It must accept a single argument that is an array of strings."

What will be the output of the program?
public class CommandArgs 
{
    public static void main(String [] args) 
    {
        String s1 = args[1];
        String s2 = args[2];
        String s3 = args[3];
        String s4 = args[4];
        System.out.print(" args[2] = " + s2);
    }
}

and the command-line invocation is

> java CommandArgs 1 2 3 4

A:
args[2] = 2
B:
args[2] = 3
C:
args[2] = null
D:
An exception is thrown at runtime.
Answer: D

An exception is thrown because in the code String s4 = args[4];, the array index (the fifth element) is out of bounds. The exception thrown is the cleverly named ArrayIndexOutOfBoundsException.

What will be the output of the program?
public class CommandArgsThree 
{
    public static void main(String [] args) 
    {
        String [][] argCopy = new String[2][2];
        int x;
        argCopy[0] = args;
        x = argCopy[0].length;
        for (int y = 0; y < x; y++) 
        {
            System.out.print(" " + argCopy[0][y]);
        }
    }
}

and the command-line invocation is

> java CommandArgsThree 1 2 3

A:
0 0
B:
1 2
C:
0 0 0
D:
1 2 3
Answer: D
In argCopy[0] = args;, the reference variable argCopy[0], which was referring to an array with two elements, is reassigned to an array (args) with three elements.
What is the numerical range of a char?
A:
-128 to 127
B:
-(215) to (215) - 1
C:
0 to 32767
D:
0 to 65535
Answer: D
A char is really a 16-bit integer behind the scenes, so it supports 216 (from 0 to 65535) values.
Which is a valid declarations of a String?
A:
String s1 = null;
B:
String s2 = 'null';
C:
String s3 = (String) 'abc';
D:
String s4 = (String) '\ufeed';
Answer: A

Option A sets the String reference to null.

Option B is wrong because null cannot be in single quotes.

Option C is wrong because there are multiple characters between the single quotes ('abc').

Option D is wrong because you can't cast a char (primitive) to a String (object).

Ad Slot (Above Pagination)
Quiz