Monday 23 July 2012

Java Language Fundamentals- Objective Questions -Part 5

1)

What will be the output of the program?


public class Test
{
    public static void main (String args[])
    {
        String str = NULL;
        System.out.println(str);
    }
}


A. NULL
B. Compile Error
C. Code runs but no output
D. Runtime Exception


Answer: B

Option B is correct because to set the value of a String  variable to null you must use "null" and not "NULL".


2)

Which four options describe the correct default values for array elements of the types
indicated?


   1. int -> 0
   2. String -> "null"
   3. Dog -> null
   4. char -> '\u0000'
   5. float -> 0.0f
   6. boolean -> true


A. 1, 2, 3, 4
B. 1, 3, 4, 5
C. 2, 4, 5, 6
D. 3, 4, 5, 6


Answer: B

(1), (3), (4), (5) are the correct statements.
(2) is wrong because the default value for a String (and any other object reference) is null, with no quotes.
(6) is wrong because the default value for boolean elements is false.


3)

Which is valid declaration of a float?


A. float f = 1F;
B. float f = 1.0;
C. float f = "1";
D. float f = 1.0d;


Answer: A

Option A is valid declaration of float.Option B is incorrect because any literal number with a decimal point you declare the computer will implicitly cast to double unless you include "F or f".Option C is incorrect because it is a String.Option D is incorrect because "d" tells the computer it is a double so therefore you are trying to put a double value into a float variable i.e there might be a loss of precision.


4)

What is the numerical range of char?


A. 0 to 32767
B. 0 to 65535
C. -256 to 255
D. -32768 to 32767


Answer: B


The char type is integral but unsigned. The range of a variable of type char is from 0 to 216-1 or 0 to 65535.Java characters are Unicode, which is a 16-bit encoding capable of representing a wide range of international characters. If the most significant nine bits of a char  are 0, then the encoding is the same as seven-bit ASCII.


5)

What will be the output of the program?


package foo;
import java.util.Vector; /* Line 2 */
private class MyVector extends Vector
{
    int i = 1; /* Line 5 */
    public MyVector()
    {
        i = 2;
    }
}
public class MyNewVector extends MyVector
{
    public MyNewVector ()
    {
        i = 4; /* Line 15 */
    }
    public static void main (String args [])
    {
        MyVector v = new MyNewVector(); /* Line 19 */
    }
}


The output of the above code is


A. Compilation will succeed.
B. Compilation will fail at line 3.
C. Compilation will fail at line 5.
D. Compilation will fail at line 15.


Answer: B


Option B is correct. The compiler complains with the error "modifier private not allowed here". The class is created private and is being used by another class on line 19.

No comments:

Post a Comment