Online Java Programming Test - Java Programming Test - Random



Loading...  Loading Test...

Instruction:

  • Total number of questions : 20.
  • Time alloted : 30 minutes.
  • Each question carry 1 mark, no negative marks.
  • DO NOT refresh the page.
  • All the best :-).

1.

What will be the output of the program?

public class Foo 
{  
    public static void main(String[] args) 
    {
        try 
        { 
            return; 
        } 
        finally 
        {
            System.out.println( "Finally" ); 
        } 
    } 
}

A.
Finally
B.
Compilation fails.
C.
The code runs with no output.
D.
An exception is thrown at runtime.

Your Answer: Option (Not Answered)

Correct Answer: Option A

Explanation:

If you put a finally block after a try and its associated catch blocks, then once execution enters the try block, the code in that finally block will definitely be executed except in the following circumstances:
  1. An exception arising in the finally block itself.
  2. The death of the thread.
  3. The use of System.exit()
  4. Turning off the power to the CPU.

I suppose the last three could be classified as VM shutdown.

Learn more problems on : Exceptions

Discuss about this problem : Discuss in Forum

2.

What will be the output of the program?

public class X 
{  
    public static void main(String [] args) 
    {
        try 
        {
            badMethod();  
            System.out.print("A");  
        } 
        catch (RuntimeException ex) /* Line 10 */
        { 
            System.out.print("B"); 
        } 
        catch (Exception ex1) 
        { 
            System.out.print("C"); 
        } 
        finally 
        {
            System.out.print("D"); 
        } 
        System.out.print("E"); 
    } 
    public static void badMethod() 
    { 
        throw new RuntimeException(); 
    } 
}

A.
BD
B.
BCD
C.
BDE
D.
BCDE

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

A Run time exception is thrown and caught in the catch statement on line 10. All the code after the finally statement is run because the exception has been caught.

Learn more problems on : Exceptions

Discuss about this problem : Discuss in Forum

3.

Which two of the following methods are defined in class Thread?

  1. start()
  2. wait()
  3. notify()
  4. run()
  5. terminate()

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

Your Answer: Option (Not Answered)

Correct Answer: Option A

Explanation:

(1) and (4). Only start() and run() are defined by the Thread class.

(2) and (3) are incorrect because they are methods of the Object class. (5) is incorrect because there's no such method in any thread-related class.

Learn more problems on : Threads

Discuss about this problem : Discuss in Forum

4.

What will be the output of the program?

class A 
{
    final public int GetResult(int a, int b) { return 0; } 
} 
class B extends A 
{ 
    public int GetResult(int a, int b) {return 1; } 
} 
public class Test 
{
    public static void main(String args[]) 
    { 
        B b = new B(); 
        System.out.println("x = " + b.GetResult(0, 1));  
    } 
}

A.
x = 0
B.
x = 1
C.
Compilation fails.
D.
An exception is thrown at runtime.

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

The code doesn't compile because the method GetResult() in class A is final and so cannot be overridden.

Learn more problems on : Declarations and Access Control

Discuss about this problem : Discuss in Forum

5.

What will be the output of the program (when you run with the -ea option) ?

public class Test 
{  
    public static void main(String[] args) 
    {
        int x = 0;  
        assert (x > 0) : "assertion failed"; /* Line 6 */
        System.out.println("finished"); 
    } 
}

A.
finished
B.
Compilation fails.
C.
An AssertionError is thrown.
D.
An AssertionError is thrown and finished is output.

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

An assertion Error is thrown as normal giving the output "assertion failed". The word "finished" is not printed (ensure you run with the -ea option)

Assertion failures are generally labeled in the stack trace with the file and line number from which they were thrown, and also in this case with the error's detail message "assertion failed". The detail message is supplied by the assert statement in line 6.

Learn more problems on : Assertions

Discuss about this problem : Discuss in Forum

6.

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() { }});

Your Answer: Option (Not Answered)

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

Learn more problems on : Inner Classes

Discuss about this problem : Discuss in Forum

7.

What will be the output of the program?

class s1 extends Thread
{ 
    public void run() 
    { 
        for(int i = 0; i < 3; i++) 
        { 
            System.out.println("A"); 
            System.out.println("B"); 
        } 
    } 
} 
class Test120 extends Thread 
{ 
    public void run() 
    { 
        for(int i = 0; i < 3; i++) 
        { 
            System.out.println("C"); 
            System.out.println("D"); 
        } 
    } 
    public static void main(String args[]) 
        { 
        s1 t1 = new s1(); 
        Test120 t2 = new Test120(); 
        t1.start(); 
        t2.start(); 
    } 
}

A.
Compile time Error There is no start() method
B.
Will print in this order AB CD AB...
C.
Will print but not be able to predict the Order
D.
Will print in this order ABCD...ABCD...

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

We cannot predict the order in which threads are going to run.

Learn more problems on : Threads

Discuss about this problem : Discuss in Forum

8.

What will be the output of the program?

public class NFE 
{
    public static void main(String [] args) 
    {
    String s = "42";
        try 
        {
            s = s.concat(".5");  /* Line 8 */
            double d = Double.parseDouble(s);
            s = Double.toString(d);
            int x = (int) Math.ceil(Double.valueOf(s).doubleValue());
            System.out.println(x);
        }
        catch (NumberFormatException e) 
        {
            System.out.println("bad number");
        }
    }
}

A.
42
B.
42.5
C.
43
D.
bad number

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

All of this code is legal, and line 8 creates a new String with a value of "42.5". Lines 9 and 10 convert the String to a double and then back again. Line 11 is fun— Math.ceil()'s argument expression is evaluated first. We invoke the valueOf() method that returns an anonymous Double object (with a value of 42.5). Then the doubleValue() method is called (invoked on the newly created Double object), and returns a double primitive (there and back again), with a value of (you guessed it) 42.5. The ceil() method converts this to 43.0, which is cast to an int and assigned to x.

Learn more problems on : Java.lang Class

Discuss about this problem : Discuss in Forum

9.

What will be the output of the program?

interface Foo141 
{ 
    int k = 0; /* Line 3 */
} 
public class Test141 implements Foo141 
{
    public static void main(String args[]) 
    {
        int i; 
        Test141 test141 = new Test141(); 
        i = test141.k; /* Line 11 */
        i = Test141.k; 
        i = Foo141.k; 
    } 
}

A.
Compilation fails.
B.
Compiles and runs ok.
C.
Compiles but throws an Exception at runtime.
D.
Compiles but throws a RuntimeException at runtime.

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

The variable k on line 3 is an interface constant, it is implicitly public, static, and final. Static variables can be referenced in two ways:

Via a reference to any instance of the class (line 11)

Via the class name (line 12).

Learn more problems on : Java.lang Class

Discuss about this problem : Discuss in Forum

10.

What will be the output of the program?

public class ExamQuestion7 
{  
    static int j; 
    static void methodA(int i)
    {
        boolean b; 
        do
        { 
            b = i<10 | methodB(4); /* Line 9 */
            b = i<10 || methodB(8);  /* Line 10 */
        }while (!b); 
    } 
    static boolean methodB(int i)
    {
        j += i; 
        return true; 
    } 
    public static void main(String[] args)
    {
        methodA(0); 
        System.out.println( "j = " + j ); 
    } 
}

A.
j = 0
B.
j = 4
C.
j = 8
D.
The code will run with no output

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

The lines to watch here are lines 9 & 10. Line 9 features the non-shortcut version of the OR operator so both of its operands will be evaluated and therefore methodB(4) is executed.

However line 10 has the shortcut version of the OR operator and if the 1st of its operands evaluates to true (which in this case is true), then the 2nd operand isn't evaluated, so methodB(8) never gets called.

The loop is only executed once, b is initialized to false and is assigned true on line 9. Thus j = 4.

Learn more problems on : Java.lang Class

Discuss about this problem : Discuss in Forum

11.

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.

Your Answer: Option (Not Answered)

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

Learn more problems on : Language Fundamentals

Discuss about this problem : Discuss in Forum

12.

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

Your Answer: Option (Not Answered)

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

Learn more problems on : Language Fundamentals

Discuss about this problem : Discuss in Forum

13.

class A 
{  
    protected int method1(int a, int b) 
    {
        return 0; 
    } 
}
Which is valid in a class that extends class A?

A.
public int method1(int a, int b) {return 0; }
B.
private int method1(int a, int b) { return 0; }
C.
public short method1(int a, int b) { return 0; }
D.
static protected int method1(int a, int b) { return 0; }

Your Answer: Option (Not Answered)

Correct Answer: Option A

Explanation:

Option A is correct - because the class that extends A is just simply overriding method1.

Option B is wrong - because it can't override as there are less access privileges in the subclass method1.

Option C is wrong - because to override it, the return type needs to be an integer. The different return type means that the method is not overriding but the same argument list means that the method is not overloading. Conflict - compile time error.

Option D is wrong - because you can't override a method and make it a class method i.e. using static.

Learn more problems on : Declarations and Access Control

Discuss about this problem : Discuss in Forum

14.

What will be the output of the program?

int i = 0; 
while(1) 
{
    if(i == 4) 
    {
        break;
    } 
    ++i; 
} 
System.out.println("i = " + i);

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

Your Answer: Option (Not Answered)

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

Learn more problems on : Flow Control

Discuss about this problem : Discuss in Forum

15.

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

Your Answer: Option (Not Answered)

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

Learn more problems on : Flow Control

Discuss about this problem : Discuss in Forum

16.

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

Your Answer: Option (Not Answered)

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

Learn more problems on : Flow Control

Discuss about this problem : Discuss in Forum

17.

    
import java.awt.*;
class Ticker extends Component 
{
    public static void main (String [] args) 
    {
        Ticker t = new Ticker();
        /* Missing Statements ? */
    }
}
which two of the following statements, inserted independently, could legally be inserted into missing section of this code?
  1. boolean test = (Component instanceof t);
  2. boolean test = (t instanceof Ticker);
  3. boolean test = t.instanceof(Ticker);
  4. boolean test = (t instanceof Component);

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

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

(2) is correct because class type Ticker is part of the class hierarchy of t; therefore it is a legal use of the instanceof operator. (4) is also correct because Component is part of the hierarchy of t, because Ticker extends Component.

(1) is incorrect because the syntax is wrong. A variable (or null) always appears before the instanceof operator, and a type appears after it. (3) is incorrect because the statement is used as a method (t.instanceof(Ticker);), which is illegal.

Learn more problems on : Operators and Assignments

Discuss about this problem : Discuss in Forum

18.

What allows the programmer to destroy an object x?

A.
x.delete()
B.
x.finalize()
C.
Runtime.getRuntime().gc()
D.
Only the garbage collection system can destroy an object.

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

Option D is correct. When an object is no longer referenced, it may be reclaimed by the garbage collector. If an object declares a finalizer, the finalizer is executed before the object is reclaimed to give the object a last chance to clean up resources that would not otherwise be released. When a class is no longer needed, it may be unloaded.

Option A is wrong. I found 4 delete() methods in all of the Java class structure. They are:

  1. delete() - Method in class java.io.File : Deletes the file or directory denoted by this abstract pathname.
  2. delete(int, int) - Method in class java.lang.StringBuffer : Removes the characters in a substring of this StringBuffer.
  3. delete(int, int) - Method in interface javax.accessibility.AccessibleEditableText : Deletes the text between two indices
  4. delete(int, int) - Method in class : javax.swing.text.JTextComponent.AccessibleJTextComponent; Deletes the text between two indices

None of these destroy the object to which they belong.

Option B is wrong. I found 19 finalize() methods. The most interesting, from this questions point of view, was the finalize() method in class java.lang.Object which is called by the garbage collector on an object when garbage collection determines that there are no more references to the object. This method does not destroy the object to which it belongs.

Option C is wrong. But it is interesting. The Runtime class has many methods, two of which are:

  1. getRuntime() - Returns the runtime object associated with the current Java application.
  2. gc() - Runs the garbage collector. Calling this method suggests that the Java virtual machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the virtual machine has made its best effort to recycle all discarded objects. Interesting as this is, it doesn't destroy the object.

Learn more problems on : Garbage Collections

Discuss about this problem : Discuss in Forum

19.

What will be the output of the program?

class SSBool 
{
    public static void main(String [] args) 
    {
        boolean b1 = true;
        boolean b2 = false;
        boolean b3 = true;
        if ( b1 & b2 | b2 & b3 | b2 ) /* Line 8 */
            System.out.print("ok ");
        if ( b1 & b2 | b2 & b3 | b2 | b1 ) /*Line 10*/
            System.out.println("dokey");
    }
}

A.
ok
B.
dokey
C.
ok dokey
D.
No output is produced
E.
Compilation error

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

The & operator has a higher precedence than the | operator so that on line 8 b1 and b2 are evaluated together as are b2 & b3. The final b1 in line 10 is what causes that if test to be true. Hence it prints "dokey".

Learn more problems on : Operators and Assignments

Discuss about this problem : Discuss in Forum

20.

Which statement is true?

A.
A static method cannot be synchronized.
B.
If a class has synchronized code, multiple threads can still access the nonsynchronized code.
C.
Variables can be protected from concurrent access problems by marking them with the synchronized keyword.
D.
When a thread sleeps, it releases its locks.

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

B is correct because multiple threads are allowed to enter nonsynchronized code, even within a class that has some synchronized methods.

A is incorrect because static methods can be synchronized; they synchronize on the lock on the instance of class java.lang.Class that represents the class type.

C is incorrect because only methods—not variables—can be marked synchronized.

D is incorrect because a sleeping thread still maintains its locks.

Learn more problems on : Threads

Discuss about this problem : Discuss in Forum

Submit your test now to view the Results and Statistics with answer explanation.