Online Java Programming Test - Java Programming Test - Random



Loading...  Loading Test...

Instruction:

  • This is a FREE online test. DO NOT pay money to anyone to attend this test.
  • 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 WaitTest 
{
    public static void main(String [] args) 
    {
        System.out.print("1 ");
        synchronized(args)
        {
            System.out.print("2 ");
            try 
            {
                    args.wait(); /* Line 11 */
            }
            catch(InterruptedException e){ }
        }
        System.out.print("3 ");
    }
}

A.
It fails to compile because the IllegalMonitorStateException of wait() is not dealt with in line 11.
B.
1 2 3
C.
1 3
D.
1 2

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

1 and 2 will be printed, but there will be no return from the wait call because no other thread will notify the main thread, so 3 will never be printed. The program is essentially frozen at line 11.

A is incorrect; IllegalMonitorStateException is an unchecked exception so it doesn't have to be dealt with explicitly.

B and C are incorrect; 3 will never be printed, since this program will never terminate because it will wait forever.

Learn more problems on : Threads

Discuss about this problem : Discuss in Forum


2.

import java.io.*;
public class MyProgram 
{
    public static void main(String args[])
    {
        FileOutputStream out = null;
        try 
        {
            out = new FileOutputStream("test.txt");
            out.write(122);
        }
        catch(IOException io) 
        {
            System.out.println("IO Error.");
        }
        finally 
        {
            out.close();
        }
    }
}
and given that all methods of class FileOutputStream, including close(), throw an IOException, which of these is true?

A.
This program will compile successfully.
B.
This program fails to compile due to an error at line 4.
C.
This program fails to compile due to an error at line 6.
D.
This program fails to compile due to an error at line 18.

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

Any method (in this case, the main() method) that throws a checked exception (in this case, out.close() ) must be called within a try clause, or the method must declare that it throws the exception. Either main() must declare that it throws an exception, or the call to out.close() in the finally block must fall inside a (in this case nested) try-catch block.

Learn more problems on : Exceptions

Discuss about this problem : Discuss in Forum


3.

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

Your Answer: Option (Not Answered)

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

Learn more problems on : Language Fundamentals

Discuss about this problem : Discuss in Forum


4.

What will be the output of the program?

import java.util.*; 
class I 
{
    public static void main (String[] args) 
    {
        Object i = new ArrayList().iterator(); 
        System.out.print((i instanceof List)+","); 
        System.out.print((i instanceof Iterator)+","); 
        System.out.print(i instanceof ListIterator); 
    } 
}

A.
Prints: false, false, false
B.
Prints: false, false, true
C.
Prints: false, true, false
D.
Prints: false, true, true

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

The iterator() method returns an iterator over the elements in the list in proper sequence, it doesn't return a List or a ListIterator object.

A ListIterator can be obtained by invoking the listIterator method.

Learn more problems on : Objects and Collections

Discuss about this problem : Discuss in Forum


5.

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


6.

public class Test2 
{
    public static int x;
    public static int foo(int y) 
    {
        return y * 2;
    }
    public static void main(String [] args) 
    {
        int z = 5;
        assert z > 0; /* Line 11 */
        assert z > 2: foo(z); /* Line 12 */
        if ( z < 7 )
            assert z > 4; /* Line 14 */

        switch (z) 
        {
            case 4: System.out.println("4 ");
            case 5: System.out.println("5 ");
            default: assert z < 10;
        }

        if ( z < 10 )
            assert z > 4: z++; /* Line 22 */
        System.out.println(z);
    }
}
which line is an example of an inappropriate use of assertions?

A.
Line 11
B.
Line 12
C.
Line 14
D.
Line 22

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

Assert statements should not cause side effects. Line 22 changes the value of z if the assert statement is false.

Option A is fine; a second expression in an assert statement is not required.

Option B is fine because it is perfectly acceptable to call a method with the second expression of an assert statement.

Option C is fine because it is proper to call an assert statement conditionally.

Learn more problems on : Assertions

Discuss about this problem : Discuss in Forum


7.

public interface Foo 
{ 
    int k = 4; /* Line 3 */
}
Which three piece of codes are equivalent to line 3?
  1. final int k = 4;
  2. public int k = 4;
  3. static int k = 4;
  4. abstract int k = 4;
  5. volatile int k = 4;
  6. protected int k = 4;

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

Your Answer: Option (Not Answered)

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

Learn more problems on : Language Fundamentals

Discuss about this problem : Discuss in Forum


8.

What will be the output of the program?

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

A.
AB
B.
BC
C.
ABC
D.
BCD

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

(1) A RuntimeException is thrown, this is a subclass of exception.

(2) The exception causes the try to complete abruptly (line 7) therefore line 8 is never executed.

(3) The exception is caught (line 10) and "B" is output (line 12)

(4) The finally block (line 14) is always executed and "C" is output (line 16).

(5) The exception was caught, so the program continues with line 18 and outputs "D".

Learn more problems on : Exceptions

Discuss about this problem : Discuss in Forum


9.

What will be the output of the program?

public class MyProgram 
{
    public static void main(String args[])
    {
        try 
        {
            System.out.print("Hello world ");
        }
        finally 
        {
            System.out.println("Finally executing ");
        }
    }
}

A.
Nothing. The program will not compile because no exceptions are specified.
B.
Nothing. The program will not compile because no catch clauses are specified.
C.
Hello world.
D.
Hello world Finally executing

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

Finally clauses are always executed. The program will first execute the try block, printing Hello world, and will then execute the finally block, printing Finally executing.

Option A, B, and C are incorrect based on the program logic described above. Remember that either a catch or a finally statement must follow a try. Since the finally is present, the catch is not required.

Learn more problems on : Exceptions

Discuss about this problem : Discuss in Forum


10.

What will be the output of the program?

class Two 
{
    byte x;
}

class PassO 
{
    public static void main(String [] args) 
    {
        PassO p = new PassO();
        p.start();
    }

    void start() 
    {
        Two t = new Two();
        System.out.print(t.x + " ");
        Two t2 = fix(t);
        System.out.println(t.x + " " + t2.x);
    }

    Two fix(Two tt) 
    {
        tt.x = 42;
        return tt;
    }
}

A.
null null 42
B.
0 0 42
C.
0 42 42
D.
0 0 0

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

In the fix() method, the reference variable tt refers to the same object (class Two) as the t reference variable. Updating tt.x in the fix() method updates t.x (they are one in the same object). Remember also that the instance variable x in the Two class is initialized to 0.

Learn more problems on : Operators and Assignments

Discuss about this problem : Discuss in Forum


11.

public class MyRunnable implements Runnable 
{
    public void run() 
    {
        // some code here
    }
}
which of these will create and start this thread?

A.
new Runnable(MyRunnable).start();
B.
new Thread(MyRunnable).run();
C.
new Thread(new MyRunnable()).start();
D.
new MyRunnable().start();

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

Because the class implements Runnable, an instance of it has to be passed to the Thread constructor, and then the instance of the Thread has to be started.

A is incorrect. There is no constructor like this for Runnable because Runnable is an interface, and it is illegal to pass a class or interface name to any constructor.

B is incorrect for the same reason; you can't pass a class or interface name to any constructor.

D is incorrect because MyRunnable doesn't have a start() method, and the only start() method that can start a thread of execution is the start() in the Thread class.

Learn more problems on : Threads

Discuss about this problem : Discuss in Forum


12.

public class Outer 
{ 
    public void someOuterMethod() 
    {
        //Line 5 
    } 
    public class Inner { } 
    
    public static void main(String[] argv) 
    {
        Outer ot = new Outer(); 
        //Line 10
    } 
} 

Which of the following code fragments inserted, will allow to compile?

A.
new Inner(); //At line 5
B.
new Inner(); //At line 10
C.
new ot.Inner(); //At line 10
D.
new Outer.Inner(); //At line 10

Your Answer: Option (Not Answered)

Correct Answer: Option A

Explanation:

Option A compiles without problem.

Option B gives error - non-static variable cannot be referenced from a static context.

Option C package ot does not exist.

Option D gives error - non-static variable cannot be referenced from a static context.

Learn more problems on : Declarations and Access Control

Discuss about this problem : Discuss in Forum


13.

Which three are valid method signatures in an interface?

  1. private int getArea();
  2. public float getVol(float x);
  3. public void main(String [] args);
  4. public static void main(String [] args);
  5. boolean setFlag(Boolean [] test);

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

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

(2), (3), and (5). These are all valid interface method signatures.

(1), is incorrect because an interface method must be public; if it is not explicitly declared public it will be made public implicitly. (4) is incorrect because interface methods cannot be static.

Learn more problems on : Declarations and Access Control

Discuss about this problem : Discuss in Forum


14.

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


15.

What will be the output of the program?

String x = "xyz";
x.toUpperCase(); /* Line 2 */
String y = x.replace('Y', 'y');
y = y + "abc";
System.out.println(y);

A.
abcXyZ
B.
abcxyz
C.
xyzabc
D.
XyZabc

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

Line 2 creates a new String object with the value "XYZ", but this new object is immediately lost because there is no reference to it. Line 3 creates a new String object referenced by y. This new String object has the value "xyz" because there was no "Y" in the String object referred to by x. Line 4 creates a new String object, appends "abc" to the value "xyz", and refers y to the result.

Learn more problems on : Java.lang Class

Discuss about this problem : Discuss in Forum


16.

What will be the output of the program?

String x = new String("xyz");
String y = "abc";
x = x + y;
How many String objects have been created?

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

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

Line 1 creates two, one referred to by x and the lost String "xyz". Line 2 creates one (for a total of three). Line 3 creates one more (for a total of four), the concatenated String referred to by x with a value of "xyzabc".

Learn more problems on : Java.lang Class

Discuss about this problem : Discuss in Forum


17.

What will be the output of the program?

public class ExamQuestion6 
{
    static int x; 
    boolean catch()
    {
        x++; 
        return true; 
    } 
    public static void main(String[] args)
    {
        x=0; 
        if ((catch() | catch()) || catch()) 
            x++; 
        System.out.println(x); 
    } 
}

A.
1
B.
2
C.
3
D.
Compilation Fails

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

Initially this looks like a question about the logical and logical shortcut operators "|" and "||" but on closer inspection it should be noticed that the name of the boolean method in this code is "catch". "catch" is a reserved keyword in the Java language and cannot be used as a method name. Hence Compilation will fail.

Learn more problems on : Java.lang Class

Discuss about this problem : Discuss in Forum


18.

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


19.

Which statement is true?

A.
If only one thread is blocked in the wait method of an object, and another thread executes the modify on that same object, then the first thread immediately resumes execution.
B.
If a thread is blocked in the wait method of an object, and another thread executes the notify method on the same object, it is still possible that the first thread might never resume execution.
C.
If a thread is blocked in the wait method of an object, and another thread executes the notify method on the same object, then the first thread definitely resumes execution as a direct and sole consequence of the notify call.
D.
If two threads are blocked in the wait method of one object, and another thread executes the notify method on the same object, then the first thread that executed the wait call first definitely resumes execution as a direct and sole consequence of the notify call.

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

Option B is correct - The notify method only wakes the thread. It does not guarantee that the thread will run.

Option A is incorrect - just because another thread activates the modify method in A this does not mean that the thread will automatically resume execution

Option C is incorrect - This is incorrect because as said in Answer B notify only wakes the thread but further to this once it is awake it goes back into the stack and awaits execution therefore it is not a "direct and sole consequence of the notify call"

Option D is incorrect - The notify method wakes one waiting thread up. If there are more than one sleeping threads then the choice as to which thread to wake is made by the machine rather than you therefore you cannot guarantee that the notify'ed thread will be the first waiting thread.

Learn more problems on : Threads

Discuss about this problem : Discuss in Forum


20.

Which two can be used to create a new Thread?

  1. Extend java.lang.Thread and override the run() method.
  2. Extend java.lang.Runnable and override the start() method.
  3. Implement java.lang.Thread and implement the run() method.
  4. Implement java.lang.Runnable and implement the run() method.
  5. Implement java.lang.Thread and implement the start() method.

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

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

There are two ways of creating a thread; extend (sub-class) the Thread class and implement the Runnable interface. For both of these ways you must implement (override and not overload) the public void run() method.

(1) is correct - Extending the Thread class and overriding its run method is a valid procedure.

(4) is correct - You must implement interfaces, and runnable is an interface and you must also include the run method.

(2) is wrong - Runnable is an interface which implements not Extends. Gives the error: (No interface expected here)

(3) is wrong - You cannot implement java.lang.Thread (This is a Class). (Implements Thread, gives the error: Interface expected). Implements expects an interface.

(5) is wrong - You cannot implement java.lang.Thread (This is a class). You Extend classes, and Implement interfaces. (Implements Thread, gives the error: Interface expected)

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.