Java Programming


Hello friends! Here are some MCQ based questions on JAVA that can be used for the preparation of competitive exams as well as campus recruitment. 
  

1. Which one is a valid declaration of a boolean?

A. boolean b1 = 0;
B. boolean b2 = 'false';
C. boolean b3 = false;
D. boolean b4 = Boolean.false();
E. boolean b5 = no;

Answer: Option C

Explanation:

A boolean can only be assigned the literal true or false.






2. Which three are valid declarations of a float?


float f1 = -343;
float f2 = 3.14;
float f3 = 0x12345;
float f4 = 42e7;
float f5 = 2001.0D;
float f6 = 2.81F;

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

Answer: Option C

Explanation:

(1) and (3) are integer literals (32 bits), and integers can be legally assigned to floats (also 32 bits).

(6) is correct because (F) is appended to the literal, declaring it as a float rather than a double (the default for floating point literals).

(2), (4),and (5) are all doubles.





3. Which is a valid declaration of a String?


A. String s1 = null;
B. String s2 = 'null';
C. String s3 = (String) 'abc';
D. String s4 = (String) '\ufeed';

Answer: Option A

Explanation:

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).




4. 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: Option D

Explanation:

A char is really a 16-bit integer behind the scenes, so it supports 216 (from 0 to 65535) values.




5. Which three are legal array declarations?


int [] myScores [];
char [] myChars;
int [6] myScores;
Score myScores [];
Score myScores [7];


A. 1, 2, 4
B. 2, 4, 5
C. 2, 3, 4
D. All are correct.

Answer: Option A


Explanation:

(1), (2), and (4) are legal array declarations. With an array declaration, you can place the brackets to the right or left of the identifier. Option A looks strange, but it's perfectly legal to split the brackets in a multidimensional array, and place them on both sides of the identifier. Although coding this way would only annoy your fellow programmers, for the exam, you need to know it's legal.

(3) and (5) are wrong because you can't declare an array with a size. The size is only needed when the array is actually instantiated (and the JVM needs to know how much space to allocate for the array, based on the type of array and the size).




6. 
public interface Foo 

    int k = 4; /* Line 3 */
}
Which three piece of codes are equivalent to line 3?


final int k = 4;
public int k = 4;
static int k = 4;
abstract int k = 4;
volatile int k = 4;
protected int k = 4;

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

Answer: Option A

Explanation:

(1), (2) and (3) are correct. Interfaces can have constants, which are always implicitly public, static, and final. Interface constant declarations of public, static, and final are optional in any combination.




7. Which one of the following will declare an array and initialize it with five numbers?

A. Array a = new Array(5);
B. int [] a = {23,22,21,20,19};
C. int a [] = new int[5];
D. int [5] array;

Answer: Option B

Explanation:

Option B is the legal way to declare and initialize an array with five elements.

Option A is wrong because it shows an example of instantiating a class named Array, passing the integer value 5 to the object's constructor. If you don't see the brackets, you can be certain there is no actual array object! In other words, an Array object (instance of class Array) is not the same as an array object.

Option C is wrong because it shows a legal array declaration, but with no initialization.

Option D is wrong (and will not compile) because it declares an array with a size. Arrays must never be given a size when declared.




8. Which three are valid declarations of a char?

char c1 = 064770;
char c2 = 'face';
char c3 = 0xbeef;
char c4 = \u0022;
char c5 = '\iface';
char c6 = '\uface';

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

Answer: Option B

Explanation:

(1), (3), and (6) are correct. char c1 = 064770; is an octal representation of the integer value 27128, which is legal because it fits into an unsigned 16-bit integer. char c3 = 0xbeef; is a hexadecimal representation of the integer value 48879, which fits into an unsigned 16-bit integer. char c6 = '\uface'; is a Unicode representation of a character.

char c2 = 'face'; is wrong because you can't put more than one character in a char literal. The only other acceptable char literal that can go between single quotes is a Unicode value, and Unicode literals must always start with a '\u'.

char c4 = \u0022; is wrong because the single quotes are missing.

char c5 = '\iface'; is wrong because it appears to be a Unicode representation (notice the backslash), but starts with '\i' rather than '\u'.




9. Which is the valid declarations within an interface definition?

A. public double methoda();
B. public final double methoda();
C. static void methoda(double d1);
D. protected void methoda(double d1);

Answer: Option A

Explanation:

Option A is correct. A public access modifier is acceptable. The method prototypes in an interface are all abstract by virtue of their declaration, and should not be declared abstract.

Option B is wrong. The final modifier means that this method cannot be constructed in a subclass. A final method cannot be abstract.

Option C is wrong. static is concerned with the class and not an instance.

Option D is wrong. protected is not permitted when declaring a method of an interface. See information below.

Member declarations in an interface disallow the use of some declaration modifiers; you cannot use transient, volatile, or synchronized in a member declaration in an interface. Also, you may not use the private and protected specifiers when declaring members of an interface.




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

int -> 0
String -> "null"
Dog -> null
char -> '\u0000'
float -> 0.0f
boolean -> true

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

Answer: Option B

Explanation:

(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.





11. Which one of these lists contains only Java programming language keywords?

A. class, if, void, long, Int, continue
B. goto, instanceof, native, finally, default, throws
C. try, virtual, throw, final, volatile, transient
D. strictfp, constant, super, implements, do
E. byte, break, assert, switch, include

Answer: Option B

Explanation:

All the words in option B are among the 49 Java keywords. Although goto reserved as a keyword in Java, goto is not used and has no function.

Option A is wrong because the keyword for the primitive int starts with a lowercase i.

Option C is wrong because "virtual" is a keyword in C++, but not Java.

Option D is wrong because "constant" is not a keyword. Constants in Java are marked static and final.

Option E is wrong because "include" is a keyword in C, but not in Java.




12. Which will legally declare, construct, and initialize an array?

A. int [] myList = {"1", "2", "3"};
B. int [] myList = (5, 8, 2);
C. int myList [] [] = {4,9,7,0};
D. int myList [] = {4, 3, 7};

Answer: Option D

Explanation:

The only legal array declaration and assignment statement is Option D

Option A is wrong because it initializes an int array with String literals.

Option B is wrong because it use something other than curly braces for the initialization.

Option C is wrong because it provides initial values for only one dimension, although the declared array is a two-dimensional array.




13. Which is a reserved word in the Java programming language?

A. method
B. native
C. subclasses
D. reference
E. array

Answer: Option B

Explanation:

The word "native" is a valid keyword, used to modify a method declaration.

Option A, D and E are not keywords. Option C is wrong because the keyword for subclassing in Java is extends, not 'subclasses'.




14. Which is a valid keyword in java?

A. interface
B. string
C. Float
D. unsigned

Answer: Option A

Explanation:

interface is a valid keyword.

Option B is wrong because although "String" is a class type in Java, "string" is not a keyword.

Option C is wrong because "Float" is a class type. The keyword for the Java primitive is float.

Option D is wrong because "unsigned" is a keyword in C/C++ but not in Java.




15. 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: Option D

Explanation:

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.




16. 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: Option D

Explanation:

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.





17.
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: Option D

Explanation:

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."


18. What will be the output of the program?

public class TestDogs 
{
    public static void main(String [ ] args) 
    {
        Dog [ ][ ] theDogs = new Dog[3][ ];
        System.out.println(theDogs[2][0].toString());
    }
}
class Dog { }

A. null
B. theDogs
C. Compilation fails
D. An exception is thrown at runtime

Answer: Option D

Explanation:

The second dimension of the array referenced by theDogs has not been initialized. Attempting to access an uninitialized object element (System.out.println(theDogs[2][0].toString());) raises a NullPointerException.





19. What will be the output of the program ?

public class Test 
{
    public static void main(String [] args) 
    {
        signed int x = 10;
        for (int y=0; y<5; y++, x--)
            System.out.print(x + ", ");
    }
}

A. 10, 9, 8, 7, 6,
B. 9, 8, 7, 6, 5,
C. Compilation fails.
D. An exception is thrown at runtime.

Answer: Option C

Explanation:

The word "signed" is not a valid modifier keyword in the Java language. All number primitives in Java are signed. Hence the Compilation will fails.




20. 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

Answer: Option D

Explanation:

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.




21. In the given program, how many lines of output will be produced?

public class Test 
{
    public static void main(String [] args) 
    {
    int [] [] [] x = new int [3] [] [];
    int i, j;
    x[0] = new int[4][];
    x[1] = new int[2][];
    x[2] = new int[5][];
    for (i = 0; i < x.length; i++)
    {
        for (j = 0; j < x[i].length; j++) 
        {
            x[i][j] = new int [i + j + 1];
            System.out.println("size = " + x[i][j].length);
        }
    }
    }
}

A. 7
B. 9
C. 11
D. 13
E. Compilation fails

Answer: Option C

Explanation:

The loops use the array sizes (length).

It produces 11 lines of output as given below.

D:\Java>javac Test.java

D:\Java>java Test
size = 1
size = 2
size = 3
size = 4
size = 2
size = 3
size = 3
size = 4
size = 5
size = 6
size = 7
Therefore, 11 is the answer.




22. What will be the output of the program?

public class X 
{
    public static void main(String [] args) 
    {
        String names [] = new String[5];
        for (int x=0; x < args.length; x++)
            names[x] = args[x];
        System.out.println(names[2]);
    }
}
and the command line invocation is

> java X a b

A. names
B. null
C. Compilation fails
D. An exception is thrown at runtime

Answer: Option B

Explanation:

The names array is initialized with five null elements. Then elements 0 and 1 are assigned the String values "a" and "b" respectively (the command-line arguments passed to main). Elements of names array 2, 3, and 4 remain unassigned, so they have a value of null.




23. 
public void foo( boolean a, boolean b)


    if( a ) 
    {
        System.out.println("A"); /* Line 5 */
    } 
    else if(a && b) /* Line 7 */
    { 
        System.out.println( "A && B"); 
    } 
    else /* Line 11 */
    { 
        if ( !b ) 
        {
            System.out.println( "notB") ;
        } 
        else 
        {
            System.out.println( "ELSE" ) ; 
        } 
    } 
}

A. If a is true and b is true then the output is "A && B"
B. If a is true and b is false then the output is "notB"
C. If a is false and b is true then the output is "ELSE"
D. If a is false and b is false then the output is "ELSE"

Answer: Option C

Explanation:

Option C is correct. The output is "ELSE". Only when a is false do the output lines after 11 get some chance of executing.

Option A is wrong. The output is "A". When a is true, irrespective of the value of b, only the line 5 output will be executed. The condition at line 7 will never be evaluated (when a is true it will always be trapped by the line 12 condition) therefore the output will never be "A && B".

Option B is wrong. The output is "A". When a is true, irrespective of the value of b, only the line 5 output will be executed.

Option D is wrong. The output is "notB".




24.
switch(x) 

    default:  
        System.out.println("Hello"); 
}

Which two are acceptable types for x?
byte
long
char
float
Short
Long

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

Answer: Option A

Explanation:

Switch statements are based on integer expressions and since both bytes and chars can implicitly be widened to an integer, these can also be used. Also shorts can be used. Short and Long are wrapper classes and reference types can not be used as variables.




25.
public void test(int x) 

    int odd = 1; 
    if(odd) /* Line 4 */
    {
        System.out.println("odd"); 
    } 
    else 
    {
        System.out.println("even"); 
    } 
}

Which statement is true?

A. Compilation fails.
B. "odd" will always be output.
C. "even" will always be output.
D. "odd" will be output for odd values of x, and "even" for even values.

Answer: Option A

Explanation:

The compiler will complain because of incompatible types (line 4), the if expects a boolean but it gets an integer.




26. 
public class While 
{
    public void loop() 
    {
        int x= 0;
        while ( 1 ) /* Line 6 */
        {
            System.out.print("x plus one is " + (x + 1)); /* Line 8 */
        }
    }
}

Which statement is true?

A. There is a syntax error on line 1.
B. There are syntax errors on lines 1 and 6.
C. There are syntax errors on lines 1, 6, and 8.
D. There is a syntax error on line 6.

Answer: Option D

Explanation:

Using the integer 1 in the while statement, or any other looping or conditional construct for that matter, will result in a compiler error. This is old C Program syntax, not valid Java.

A, B and C are incorrect because line 1 is valid (Java is case sensitive so While is a valid class name). 

Line 8 is also valid because an equation may be placed in a String operation as shown.




27. What will be the output of the program?

int i = l, j = -1; 
switch (i) 
{
    case 0, 1: j = 1; /* Line 4 */
    case 2: j = 2; 
    default: j = 0; 

System.out.println("j = " + j); 

A. j = -1
B. j = 0
C. j = 1
D. Compilation fails.

Answer: Option D

Explanation:

The case statement takes only a single argument. The case statement on line 4 has two arguments so the compiler fails.



28. What will be the output of the program?

int i = 1, j = 10; 
do 
{
    if(i > j) 
    {
        break; 
    } 
    j--; 
} while (++i < 5); 
System.out.println("i = " + i + " and j = " + j);

A. i = 6 and j = 5
B. i = 5 and j = 5
C. i = 6 and j = 4
D. i = 5 and j = 6

Answer: Option D

Explanation:

This loop is a do-while loop, which always executes the code block within the block at least once, due to the testing condition being at the end of the loop, rather than at the beginning. This particular loop is exited prematurely if i becomes greater than j.

The order is, test i against j, if bigger, it breaks from the loop, decrements j by one, and then tests the loop condition, where a pre-incremented by one i is tested for being lower than 5. The test is at the end of the loop, so i can reach the value of 5 before it fails. So it goes, start:

1, 10

2, 9

3, 8

4, 7

5, 6 loop condition fails.




29. What will be the output of the program?

public class Switch2 
{
    final static short x = 2;
    public static int y = 0;
    public static void main(String [] args) 
    {
        for (int z=0; z < 3; z++) 
        {
            switch (z) 
            {
                case x: System.out.print("0 ");
                case x-1: System.out.print("1 ");
                case x-2: System.out.print("2 ");
            }
        }
    }
}

A. 0 1 2
B. 0 1 2 1 2 2
C. 2 1 0 1 0 0
D. 2 1 2 0 1 2

Answer: Option D

Explanation:

The case expressions are all legal because x is marked final, which means the expressions can be evaluated at compile time. In the first iteration of the for loop case x-2 matches, so 2 is printed. In the second iteration, x-1 is matched so 1 and 2 are printed (remember, once a match is found all remaining statements are executed until a break statement is encountered). In the third iteration, x is matched. So 0 1 and 2 are printed.




30. What will be the output of the program?

public class SwitchTest 
{  
    public static void main(String[] args) 
    {
        System.out.println("value =" + switchIt(4)); 
    } 
    public static int switchIt(int x) 
    {
        int j = 1;  
        switch (x) 
        { 
            case l: j++; 
            case 2: j++;  
            case 3: j++; 
            case 4: j++; 
            case 5: j++; 
            default: j++; 
            } 
        return j + x;  
    } 
}

A. value = 2
B. value = 4
C. value = 6
D. value = 8

Answer: Option D

Explanation:

Because there are no break statements, once the desired result is found, the program continues though each of the remaining options.




31. What will be the output of the program?

public class If2 
{
    static boolean b1, b2;
    public static void main(String [] args) 
    {
        int x = 0;
        if ( !b1 ) /* Line 7 */
        {
            if ( !b2 ) /* Line 9 */
            {
                b1 = true;
                x++;
                if ( 5 > 6 ) 
                {
                    x++;
                }
                if ( !b1 ) 
                    x = x + 10;
                else if ( b2 = true ) /* Line 19 */
                    x = x + 100;
                else if ( b1 | b2 ) /* Line 21 */
                    x = x + 1000;
            }
        }
        System.out.println(x);
    }
}

A. 0
B. 1
C. 101
D. 111

Answer: Option C

Explanation:

As instance variables, b1 and b2 are initialized to false. The if tests on lines 7 and 9 are successful so b1 is set to true and x is incremented. The next if test to succeed is on line 19 (note that the code is not testing to see if b2 is true, it is setting b2 to be true). Since line 19 was successful, subsequent else-if's (line 21) will be skipped.




32. What will be the output of the program?

public class Switch2 
{
    final static short x = 2;
    public static int y = 0;
    public static void main(String [] args) 
    {
        for (int z=0; z < 3; z++) 
        {
            switch (z) 
            {
                case y: System.out.print("0 ");   /* Line 11 */
                case x-1: System.out.print("1 "); /* Line 12 */
                case x: System.out.print("2 ");   /* Line 13 */
            }
        }
    }
}

A. 0 1 2
B. 0 1 2 1 2 2
C. Compilation fails at line 11.
D. Compilation fails at line 12.

Answer: Option C

Explanation:

Case expressions must be constant expressions. Since x is marked final, lines 12 and 13 are legal; however y is not a final so the compiler will fail at line 11.




33. What will be the output of the program?

public class If1 
{
    static boolean b;
    public static void main(String [] args) 
    {
        short hand = 42;
        if ( hand < 50 & !b ) /* Line 7 */
            hand++;
        if ( hand > 50 );     /* Line 9 */
        else if ( hand > 40 ) 
        {
            hand += 7;
            hand++;    
        }
        else
            --hand;
        System.out.println(hand);
    }
}

A. 41
B. 42
C. 50
D. 51

Answer: Option D

Explanation:

In Java, boolean instance variables are initialized to false, so the if test on line 7 is true and hand is incremented. Line 9 is legal syntax, a do nothing statement. The else-if is true so hand has 7 added to it and is then incremented.




34. What will be the output of the program?

public class Test 
{
    public static void main(String [] args) 
    {
        int I = 1;
        do while ( I < 1 )
        System.out.print("I is " + I);
        while ( I > 1 ) ;
    }
}

A. I is 1
B. I is 1 I is 1
C. No output is produced.
D. Compilation error

Answer: Option C

Explanation:

There are two different looping constructs in this problem. The first is a do-while loop and the second is a while loop, nested inside the do-while. The body of the do-while is only a single statement-brackets are not needed. You are assured that the while expression will be evaluated at least once, followed by an evaluation of the do-while expression. Both expressions are false and no output is produced.




35. What will be the output of the program?

int x = l, y = 6; 
while (y--) 
{
    x++; 

System.out.println("x = " + x +" y = " + y);

A. x = 6 y = 0
B. x = 7 y = 0
C. x = 6 y = -1
D. Compilation fails.

Answer: Option D

Explanation:

Compilation fails because the while loop demands a boolean argument for it's looping condition, but in the code, it's given an int argument.

while(true) { //insert code here }




36. What will be the output of the program?

int I = 0;
    outer:
    while (true) 
    {
        I++;
        inner:
        for (int j = 0; j < 10; j++) 
        {
            I += j;
            if (j == 3)
                continue inner;
            break outer;
        }
        continue outer;
    }
System.out.println(I);

A. 1
B. 2
C. 3
D. 4

Answer: Option A

Explanation:

The program flows as follows: I will be incremented after the while loop is entered, then I will be incremented (by zero) when the for loop is entered. The if statement evaluates to false, and the continue statement is never reached. The break statement tells the JVM to break out of the outer loop, at which point I is printed and the fragment is done.




37. What will be the output of the program?

for (int i = 0; i < 4; i += 2) 

    System.out.print(i + " "); 

System.out.println(i); /* Line 5 */

A. 0 2 4
B. 0 2 4 5
C. 0 1 2 3 4
D. Compilation fails.

Answer: Option D

Explanation:

Compilation fails on the line 5 - System.out.println(i); as the variable i has only been declared within the for loop. It is not a recognised variable outside the code block of loop.




38. What will be the output of the program?

int x = 3; 
int y = 1; 
if (x = y) /* Line 3 */
{
    System.out.println("x =" + x); 
}

A. x = 1
B. x = 3
C. Compilation fails.
D. The code runs with no output.

Answer: Option C

Explanation:

Line 3 uses an assignment as opposed to comparison. Because of this, the if statement receives an integer value instead of a boolean. And so the compilation fails.




39. What will be the output of the program?

Float f = new Float("12"); 
switch (f) 
{
    case 12: System.out.println("Twelve"); 
    case 0: System.out.println("Zero"); 
    default: System.out.println("Default"); 
}

A. Zero
B. Twelve
C. Default
D. Compilation fails

Answer: Option D

Explanation:

The switch statement can only be supported by integers or variables more "narrow" than an integer i.e. byte, char, short. Here a Float wrapper object is used and so the compilation fails.




40. What will be the output of the program?

int i = O; 
while(1) 
{
    if(i == 4) 
    {
        break;
    } 
    ++i; 

System.out.println("i = " + i);

A. i = 0
B. i = 3
C. i = 4
D. Compilation fails.

Answer: Option D

Explanation:

Compilation fails because the argument of the while loop, the condition, must be of primitive type boolean. 

In Java, 1 does not represent the true state of a boolean, rather it is seen as an integer.




41. What will be the output of the program?

public class Delta 

    static boolean foo(char c) 
    {
        System.out.print(c); 
        return true; 
    } 
    public static void main( String[] argv ) 
    {
        int i = 0; 
        for (foo('A'); foo('B') && (i < 2); foo('C')) 
        {
            i++; 
            foo('D'); 
        } 
    } 
}

A. ABDCBDCB
B. ABCDABCD
C. Compilation fails.
D. An exception is thrown at runtime.

Answer: Option A

Explanation:

'A' is only printed once at the very start as it is in the initialisation section of the for loop. The loop will only initialise that once.

'B' is printed as it is part of the test carried out in order to run the loop.

'D' is printed as it is in the loop.

'C' is printed as it is in the increment section of the loop and will 'increment' only at the end of each loop. 

Here ends the first loop. Again 'B' is printed as part of the loop test.

'D' is printed as it is in the loop.

'C' is printed as it 'increments' at the end of each loop.

Again 'B' is printed as part of the loop test. At this point the test fails because the other part of the test (i < 2) is no longer true. i has been increased in value by 1 for each loop with the line: i++;

This results in a printout of ABDCBDCB




42. What will be the output of the program?

for(int i = 0; i < 3; i++) 

    switch(i) 
    { 
        case 0: break; 
        case 1: System.out.print("one "); 
        case 2: System.out.print("two "); 
        case 3: System.out.print("three "); 
    } 

System.out.println("done");

A. done
B. one two done
C. one two three done
D. one two three two three done

Answer: Option D

Explanation:

The variable i will have the values 0, 1 and 2.

When i is 0, nothing will be printed because of the break in case 0.

When i is 1, "one two three" will be output because case 1, case 2 and case 3 will be executed (they don't have break statements).

When i is 2, "two three" will be output because case 2 and case 3 will be executed (again no break statements).

Finally, when the for loop finishes "done" will be output.




43. What will be the output of the program?

public class Test 
{  
    public static void main(String args[]) 
    { 
        int i = 1, j = 0; 
        switch(i) 
        { 
            case 2: j += 6; 
            case 4: j += 1; 
            default: j += 2; 
            case 0: j += 4; 
        } 
        System.out.println("j = " + j); 
    } 
}

A. 0
B. 2
C. 4
D. 6

Answer: Option D

Explanation:

Because there are no break statements, the program gets to the default case and adds 2 to j, then goes to case 0 and adds 4 to the new j. 

The result is j = 6.




44. What will be the output of the program?

boolean bool = true; 
if(bool = false) /* Line 2 */
{
    System.out.println("a"); 

else if(bool) /* Line 6 */
{
    System.out.println("b"); 

else if(!bool) /* Line 10 */
{
    System.out.println("c"); /* Line 12 */

else 
{
    System.out.println("d"); 
}

A. a
B. b
C. c
D. d

Answer: Option C

Explanation:

Look closely at line 2, is this an equality check (==) or an assignment (=). The condition at line 2 evaluates to false and also assigns false to bool. bool is now false so the condition at line 6 is not true. The condition at line 10 checks to see if bool is not true ( if !(bool == true) ), it isn't so line 12 is executed.




45. What will be the output of the program?

public class Switch2 
{
    final static short x = 2;
    public static int y = 0;
    public static void main(String [] args) 
    {
        for (int z=0; z < 4; z++) 
        {
            switch (z) 
            {
                case x: System.out.print("0 ");
                default: System.out.print("def ");
                case x-1: System.out.print("1 ");  
                            break;
                case x-2: System.out.print("2 ");
            }
        }
    }
}

A. 0 def 1
B. 2 1 0 def 1
C. 2 1 0 def def
D. 2 1 0 def 1 def 1

Answer: Option D

Explanation:

When z == 0 , case x-2 is matched. When z == 1, case x-1 is matched and then the break occurs. When z == 2, case x, then default, then x-1 are all matched. When z == 3, default, then x-1 are matched. The rules for default are that it will fall through from above like any other case (for instance when z == 2), and that it will match when no other cases match (for instance when z==3).




46. What will be the output of the program?

int i = 0, j = 5; 
tp: for (;;) 
    {
        i++;  
        for (;;) 
        {
            if(i > --j) 
            {
                break tp; 
            } 
        } 
        System.out.println("i =" + i + ", j = " + j);

A. i = 1, j = 0
B. i = 1, j = 4
C. i = 3, j = 4
D. Compilation fails.

Answer: Option D

Explanation:

If you examine the code carefully you will notice a missing curly bracket at the end of the code, this would cause the code to fail.




47. What will be the output of the program?

int I = 0;
label:
    if (I < 2) {
    System.out.print("I is " + I);
    I++;
    continue label;
}

A. I is 0
B. I is 0 I is 1
C. Compilation fails.
D. None of the above

Answer: Option C

Explanation:

The code will not compile because a continue statement can only occur in a looping construct.




48. Which is true about an anonymous inner class?


A. It can extend exactly one class and implement exactly one interface.
B. It can extend exactly one class and can implement multiple interfaces.
C. It can extend exactly one class or implement exactly one interface.
D. It can implement multiple interfaces regardless of whether it also extends a class.

Answer: Option C

Explanation:

Option C is correct because the syntax of an anonymous inner class allows for only one named type after the new, and that type must be either a single interface (in which case the anonymous class implements that one interface) or a single class (in which case the anonymous class extends that one class).

Option A, B, D, and E are all incorrect because they don't follow the syntax rules described in the response for answer Option C.




49.
class Boo 
{
    Boo(String s) { }
    Boo() { }
}
class Bar extends Boo 
{
    Bar() { }
    Bar(String s) {super(s);}
    void zoo() 
    {
    // insert code here
    }
}

which one create an anonymous inner class from within class Bar?

A. Boo f = new Boo(24) { };
B. Boo f = new Bar() { };
C. Bar f = new Boo(String s) { };
D. Boo f = new Boo.Bar(String s) { };

Answer: Option B

Explanation:

Option B is correct because anonymous inner classes are no different from any other class when it comes to polymorphism. That means you are always allowed to declare a reference variable of the superclass type and have that reference variable refer to an instance of a subclass type, which in this case is an anonymous subclass of Bar. Since Bar is a subclass of Boo, it all works.

Option A is incorrect because it passes an int to the Boo constructor, and there is no matching constructor in the Boo class.

Option C is incorrect because it violates the rules of polymorphism—you cannot refer to a superclass type using a reference variable declared as the subclass type. The superclass is not guaranteed to have everything the subclass has.

Option D uses incorrect syntax.




50. Which is true about a method-local inner class?

A. It must be marked final.
B. It can be marked abstract.
C. It can be marked public.
D. It can be marked static.

Answer: Option B

Explanation:b

Option B is correct because a method-local inner class can be abstract, although it means a subclass of the inner class must be created if the abstract class is to be used (so an abstract method-local inner class is probably not useful).

Option A is incorrect because a method-local inner class does not have to be declared final (although it is legal to do so).

C and D are incorrect because a method-local inner class cannot be made public (remember-you cannot mark any local variables as public), or static.




51. Which statement is true about a static nested class?

A. You must have a reference to an instance of the enclosing class in order to instantiate it.
B. It does not have access to nonstatic members of the enclosing class.
C. It's variables and methods must be static.
D. It must extend the enclosing class.

Answer: Option B

Explanation:

Option B is correct because a static nested class is not tied to an instance of the enclosing class, and thus can't access the nonstatic members of the class (just as a static method can't access nonstatic members of a class).

Option A is incorrect because static nested classes do not need (and can't use) a reference to an instance of the enclosing class.

Option C is incorrect because static nested classes can declare and define nonstatic members.

Option D is wrong because it just is. There's no rule that says an inner or nested class has to extend anything.




52. Which constructs an anonymous inner class instance?

A. Runnable r = new Runnable() { };
B. Runnable r = new Runnable(public void run() { });
C. Runnable r = new Runnable { public void run(){}};
D. System.out.println(new Runnable() {public void run() { }});

Answer: Option D

Explanation:

D is correct. It defines an anonymous inner class instance, which also means it creates an instance of that new anonymous class at the same time. The anonymous class is an implementer of the Runnable interface, so it must override the run() method of Runnable.

A is incorrect because it doesn't override the run() method, so it violates the rules of interface implementation.

B and C use incorrect syntax.




53. 
class Foo 
{
    class Bar{ }
}
class Test 
{
    public static void main (String [] args) 
    {
        Foo f = new Foo();
        /* Line 10: Missing statement ? */
    }
}

which statement, inserted at line 10, creates an instance of Bar?

A. Foo.Bar b = new Foo.Bar();
B. Foo.Bar b = f.new Bar();
C. Bar b = new f.Bar();
D. Bar b = f.new Bar();

Answer: Option B

Explanation:

Option B is correct because the syntax is correct-using both names (the enclosing class and the inner class) in the reference declaration, then using a reference to the enclosing class to invoke new on the inner class.

Option A, C and D all use incorrect syntax. A is incorrect because it doesn't use a reference to the enclosing class, and also because it includes both names in the new.

C is incorrect because it doesn't use the enclosing class name in the reference variable declaration, and because the new syntax is wrong.

D is incorrect because it doesn't use the enclosing class name in the reference variable declaration.




54. 
public class MyOuter 
{
    public static class MyInner 
    {
        public static void foo() { }
    }
}

which statement, if placed in a class other than MyOuter or MyInner, instantiates an instance of the nested class?

A. MyOuter.MyInner m = new MyOuter.MyInner();
B. MyOuter.MyInner mi = new MyInner();
C. MyOuter m = new MyOuter();
    MyOuter.MyInner mi = m.new MyOuter.MyInner();
D. MyInner mi = new MyOuter.MyInner();

Answer: Option A

Explanation:

MyInner is a static nested class, so it must be instantiated using the fully-scoped name of MyOuter.MyInner.

Option B is incorrect because it doesn't use the enclosing name in the new.

Option C is incorrect because it uses incorrect syntax. When you instantiate a nested class by invoking new on an instance of the enclosing class, you do not use the enclosing name. The difference between Option A and C is that Option C is calling new on an instance of the enclosing class rather than just new by itself.

Option D is incorrect because it doesn't use the enclosing class name in the variable declaration.




55. What will be the output of the program?

public class Foo 
{
    Foo() 
    {
        System.out.print("foo");
    }
    
class Bar
{
    Bar() 
    {
        System.out.print("bar");
    }
    public void go() 
    {
        System.out.print("hi");
    }
} /* class Bar ends */

    public static void main (String [] args) 
    {
        Foo f = new Foo();
        f.makeBar();
    }
    void makeBar() 
    {
        (new Bar() {}).go();
    }
}/* class Foo ends */

A. Compilation fails.
B. An error occurs at runtime.
C. It prints "foobarhi"
D. It prints "barhi"

Answer: Option C

Explanation:

Option C is correct because first the Foo instance is created, which means the Foo constructor runs and prints "foo". Next, the makeBar() method is invoked which creates a Bar, which means the Bar constructor runs and prints "bar", and finally the go() method is invoked on the new Bar instance, which means the go() method prints "hi".




56. What will be the output of the program?

public class HorseTest 
{
    public static void main (String [] args) 
    {
        class Horse 
        {
            public String name; /* Line 7 */
            public Horse(String s) 
            {
                name = s;
            }
        } /* class Horse ends */
        
        Object obj = new Horse("Zippo"); /* Line 13 */
        Horse h = (Horse) obj; /* Line 14 */
        System.out.println(h.name);
    }
} /* class HorseTest ends */

A. An exception occurs at runtime at line 10.
B. It prints "Zippo".
C. Compilation fails because of an error on line 7.
D. Compilation fails because of an error on line 13.

Answer: Option B

Explanation:

The code in the HorseTest class is perfectly legal. Line 13 creates an instance of the method-local inner class Horse, using a reference variable declared as type Object. Line 14 casts the Horse object to a Horse reference variable, which allows line 15 to compile. If line 14 were removed, the HorseTest code would not compile, because class Object does not have a name variable.




57. What will be the output of the program?

public class TestObj 
{
    public static void main (String [] args) 
    {
        Object o = new Object() /* Line 5 */
        {
            public boolean equals(Object obj) 
            {
                return true;
            } 
        }      /* Line 11 */
        
        System.out.println(o.equals("Fred"));
    }
}

A. It prints "true".
B. It prints "Fred".
C. An exception occurs at runtime.
D. Compilation fails

Answer: Option D

Explanation:

This code would be legal if line 11 ended with a semicolon. Remember that line 5 is a statement that doesn't end until line 11, and a statement needs a closing semicolon!




58. What will be the output of the program?

public abstract class AbstractTest 
{
    public int getNum() 
    {
        return 45;
    }
    public abstract class Bar 
    {
        public int getNum() 
        {
            return 38;
        }
    }
    public static void main (String [] args) 
    {
        AbstractTest t = new AbstractTest() 
        {
            public int getNum() 
            {
                return 22;
            }
        };
        AbstractTest.Bar f = t.new Bar() 
        {
            public int getNum() 
            {
                return 57;
            }
        };
        
        System.out.println(f.getNum() + " " + t.getNum());
    }
}

A. 57 22
B. 45 38
C. 45 57
D. An exception occurs at runtime.

Answer: Option A

Explanation:

You can define an inner class as abstract, which means you can instantiate only concrete subclasses of the abstract inner class. The object referenced by the variable t is an instance of an anonymous subclass of AbstractTest, and the anonymous class overrides the getNum() method to return 22. The variable referenced by f is an instance of an anonymous subclass of Bar, and the anonymous Bar subclass also overrides the getNum() method (to return 57). Remember that to instantiate a Bar instance, we need an instance of the enclosing AbstractTest class to tie to the new Bar inner class instance. AbstractTest can't be instantiated because it's abstract, so we created an anonymous subclass (non-abstract) and then used the instance of that anonymous subclass to tie to the new Bar subclass instance.


1 comment:

Note: only a member of this blog may post a comment.