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 A
{ 
    void A() /* Line 3 */
    {
        System.out.println("Class A"); 
    } 
    public static void main(String[] args) 
    { 
        new A(); 
    } 
}

A.
Class A
B.
Compilation fails.
C.
An exception is thrown at line 3.
D.
The code executes with no output.

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

Option D is correct. The specification at line 3 is for a method and not a constructor and this method is never called therefore there is no output. The constructor that is called is the default constructor.

Learn more problems on : Declarations and Access Control

Discuss about this problem : Discuss in Forum


2.

What will be the output of the program?

import java.util.*;
public class NewTreeSet2 extends NewTreeSet 
{
    public static void main(String [] args) 
    {
        NewTreeSet2 t = new NewTreeSet2();
        t.count();
    }
}
protected class NewTreeSet
{
    void count() 
    {
        for (int x = 0; x < 7; x++,x++ ) 
        {
            System.out.print(" " + x);
        }
    }
}

A.
0 2 4
B.
0 2 4 6
C.
Compilation fails at line 2
D.
Compilation fails at line 10

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

Nonnested classes cannot be marked protected (or final for that matter), so the compiler will fail at protected class NewTreeSet.

Learn more problems on : Declarations and Access Control

Discuss about this problem : Discuss in Forum


3.

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


4.

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.

Your Answer: Option (Not Answered)

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

Learn more problems on : Inner Classes

Discuss about this problem : Discuss in Forum


5.

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;

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

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

Learn more problems on : Language Fundamentals

Discuss about this problem : Discuss in Forum


6.

What will be the output of the program?

try 
{ 
    int x = 0; 
    int y = 5 / x; 
} 
catch (Exception e) 
{
    System.out.println("Exception"); 
} 
catch (ArithmeticException ae) 
{
    System.out.println(" Arithmetic Exception"); 
} 
System.out.println("finished");

A.
finished
B.
Exception
C.
Compilation fails.
D.
Arithmetic Exception

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

Compilation fails because ArithmeticException has already been caught. ArithmeticException is a subclass of java.lang.Exception, by time the ArithmeticException has been specified it has already been caught by the Exception class.

If ArithmeticException appears before Exception, then the file will compile. When catching exceptions the more specific exceptions must be listed before the more general (the subclasses must be caught before the superclasses).

Learn more problems on : Exceptions

Discuss about this problem : Discuss in Forum


7.

What will be the output of the program?

public class X 
{ 
    public static void main(String [] args) 
    {
        try 
        {
            badMethod();  
            System.out.print("A"); 
        }  
        catch (Exception ex) 
        {
            System.out.print("B"); 
        }  
        finally 
        {
            System.out.print("C"); 
        }  
        System.out.print("D"); 
    }  
    public static void badMethod() {} 
} 

A.
AC
B.
BC
C.
ACD
D.
ABCD

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

There is no exception thrown, so all the code with the exception of the catch statement block is run.

Learn more problems on : Exceptions

Discuss about this problem : Discuss in Forum


8.

Which collection class allows you to associate its elements with key values, and allows you to retrieve objects in FIFO (first-in, first-out) sequence?

A.
java.util.ArrayList
B.
java.util.LinkedHashMap
C.
java.util.HashMap
D.
java.util.TreeMap

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

LinkedHashMap is the collection class used for caching purposes. FIFO is another way to indicate caching behavior. To retrieve LinkedHashMap elements in cached order, use the values() method and iterate over the resultant collection.

Learn more problems on : Objects and Collections

Discuss about this problem : Discuss in Forum


9.

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.

Your Answer: Option (Not Answered)

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

Learn more problems on : Flow Control

Discuss about this problem : Discuss in Forum


10.

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

Your Answer: Option (Not Answered)

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

Learn more problems on : Flow Control

Discuss about this problem : Discuss in Forum


11.


package testpkg.p1;
public class ParentUtil 
{
    public int x = 420;
    protected int doStuff() { return x; }
}

package testpkg.p2;
import testpkg.p1.ParentUtil;
public class ChildUtil extends ParentUtil 
{
    public static void main(String [] args) 
    {
        new ChildUtil().callStuff();
    }
    void callStuff() 
    {
        System.out.print("this " + this.doStuff() ); /* Line 18 */
        ParentUtil p = new ParentUtil();
        System.out.print(" parent " + p.doStuff() ); /* Line 20 */
    }
}
which statement is true?

A.
The code compiles and runs, with output this 420 parent 420.
B.
If line 18 is removed, the code will compile and run.
C.
If line 20 is removed, the code will compile and run.
D.
An exception is thrown at runtime.

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

The ParentUtil instance p cannot be used to access the doStuff() method. Because doStuff() has protected access, and the ChildUtil class is not in the same package as the ParentUtil class, doStuff() can be accessed only by instances of the ChildUtil class (a subclass of ParentUtil).

Option A, B and D are incorrect because of the access rules described previously.

Learn more problems on : Declarations and Access Control

Discuss about this problem : Discuss in Forum


12.

Which two statements are true?

  1. Deadlock will not occur if wait()/notify() is used
  2. A thread will resume execution as soon as its sleep duration expires.
  3. Synchronization can prevent two objects from being accessed by the same thread.
  4. The wait() method is overloaded to accept a duration.
  5. The notify() method is overloaded to accept a duration.
  6. Both wait() and notify() must be called from a synchronized context.

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

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

Statements (4) and (6) are correct. (4) is correct because the wait() method is overloaded to accept a wait duration in milliseconds. If the thread has not been notified by the time the wait duration has elapsed, then the thread will move back to runnable even without having been notified.

(6) is correct because wait()/notify()/notifyAll() must all be called from within a synchronized, context. A thread must own the lock on the object its invoking wait()/notify()/notifyAll() on.

(1) is incorrect because wait()/notify() will not prevent deadlock.

(2) is incorrect because a sleeping thread will return to runnable when it wakes up, but it might not necessarily resume execution right away. To resume executing, the newly awakened thread must still be moved from runnable to running by the scheduler.

(3) is incorrect because synchronization prevents two or more threads from accessing the same object.

(5) is incorrect because notify() is not overloaded to accept a duration.

Learn more problems on : Threads

Discuss about this problem : Discuss in Forum


13.

Which of the following statements is true?

A.
If assertions are compiled into a source file, and if no flags are included at runtime, assertions will execute by default.
B.
As of Java version 1.4, assertion statements are compiled by default.
C.
With the proper use of runtime arguments, it is possible to instruct the VM to disable assertions for a certain class, and to enable assertions for a certain package, at the same time.
D.
When evaluating command-line arguments, the VM gives -ea flags precedence over -da flags.

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

Option C is true because multiple VM flags can be used on a single invocation of a Java program.

Option A is incorrect because at runtime assertions are ignored by default.

Option B is incorrect because as of Java 1.4 you must add the argument -source 1.4 to the command line if you want the compiler to compile assertion statements.

Option D is incorrect because the VM evaluates all assertion flags left to right.

Learn more problems on : Assertions

Discuss about this problem : Discuss in Forum


14.

Which of the following statements is true?

A.
It is sometimes good practice to throw an AssertionError explicitly.
B.
Private getter() and setter() methods should not use assertions to verify arguments.
C.
If an AssertionError is thrown in a try-catch block, the finally block will be bypassed.
D.
It is proper to handle assertion statement failures using a catch (AssertionException ae) block.

Your Answer: Option (Not Answered)

Correct Answer: Option A

Explanation:

Option A is correct because it is sometimes advisable to thrown an assertion error even if assertions have been disabled.

Option B is incorrect because it is considered appropriate to check argument values in private methods using assertions.

Option C is incorrect; finally is never bypassed.

Option D is incorrect because AssertionErrors should never be handled.

Learn more problems on : Assertions

Discuss about this problem : Discuss in Forum


15.

Which statement is true?

A.
Assertions can be enabled or disabled on a class-by-class basis.
B.
Conditional compilation is used to allow tested classes to run at full speed.
C.
Assertions are appropriate for checking the validity of arguments in a method.
D.
The programmer can choose to execute a return statement or to throw an exception if an assertion fails.

Your Answer: Option (Not Answered)

Correct Answer: Option A

Explanation:

Option A is correct. The assertion status can be set for a named top-level class and any nested classes contained therein. This setting takes precedence over the class loader's default assertion status, and over any applicable per-package default. If the named class is not a top-level class, the change of status will have no effect on the actual assertion status of any class.

Option B is wrong. Is there such a thing as conditional compilation in Java?

Option C is wrong. For private methods - yes. But do not use assertions to check the parameters of a public method. An assert is inappropriate in public methods because the method guarantees that it will always enforce the argument checks. A public method must check its arguments whether or not assertions are enabled. Further, the assert construct does not throw an exception of the specified type. It can throw only an AssertionError.

Option D is wrong. Because you're never supposed to handle an assertion failure. That means don't catch it with a catch clause and attempt to recover.

Learn more problems on : Assertions

Discuss about this problem : Discuss in Forum


16.

What will be the output of the program?

public class Test 
{ 
    private static float[] f = new float[2]; 
    public static void main (String[] args) 
    {
        System.out.println("f[0] = " + f[0]); 
    } 
}

A.
f[0] = 0
B.
f[0] = 0.0
C.
Compile Error
D.
Runtime Exception

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

The choices are between Option A and B, what this question is really testing is your knowledge of default values of an initialized array. This is an array type float i.e. it is a type that uses decimal point numbers therefore its initial value will be 0.0 and not 0

Learn more problems on : Objects and Collections

Discuss about this problem : Discuss in Forum


17.

Which two statements are equivalent?

  1. 3/2
  2. 3<2
  3. 3*4
  4. 3<<2

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

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

(1) is wrong. 3/2 = 1 (integer arithmetic).

(2) is wrong. 3 < 2 = false.

(3) is correct. 3 * 4 = 12.

(4) is correct. 3 <<2= 12. In binary 3 is 11, now shift the bits two places to the left and we get 1100 which is 12 in binary (3*2*2).

Learn more problems on : Operators and Assignments

Discuss about this problem : Discuss in Forum


18.

import java.awt.Button;
class CompareReference 
{
    public static void main(String [] args) 
    {
        float f = 42.0f;
        float [] f1 = new float[2];
        float [] f2 = new float[2];
        float [] f3 = f1;
        long x = 42;
        f1[0] = 42.0f;
    }
}
which three statements are true?
  1. f1 == f2
  2. f1 == f3
  3. f2 == f1[1]
  4. x == f1[0]
  5. f == f1[0]

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

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

(2) is correct because the reference variables f1 and f3 refer to the same array object.

(4) is correct because it is legal to compare integer and floating-point types.

(5) is correct because it is legal to compare a variable with an array element.

(3) is incorrect because f2 is an array object and f1[1] is an array element.

Learn more problems on : Operators and Assignments

Discuss about this problem : Discuss in Forum


19.

Which cannot directly cause a thread to stop executing?

A.
Calling the SetPriority() method on a Thread object.
B.
Calling the wait() method on an object.
C.
Calling notify() method on an object.
D.
Calling read() method on an InputStream object.

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

Option C is correct. notify() - wakes up a single thread that is waiting on this object's monitor.

Learn more problems on : Threads

Discuss about this problem : Discuss in Forum


20.

class Test 
{  
    private Demo d; 
    void start() 
    {  
        d = new Demo(); 
        this.takeDemo(d); /* Line 7 */
    } /* Line 8 */
    void takeDemo(Demo demo) 
    { 
        demo = null;  
        demo = new Demo(); 
    } 
}
When is the Demo object eligible for garbage collection?

A.
After line 7
B.
After line 8
C.
After the start() method completes
D.
When the instance running this code is made eligible for garbage collection.

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

Option D is correct. By a process of elimination.

Option A is wrong. The variable d is a member of the Test class and is never directly set to null.

Option B is wrong. A copy of the variable d is set to null and not the actual variable d.

Option C is wrong. The variable d exists outside the start() method (it is a class member). So, when the start() method finishes the variable d still holds a reference.

Learn more problems on : Garbage Collections

Discuss about this problem : Discuss in Forum


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