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.

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


2.

You want subclasses in any package to have access to members of a superclass. Which is the most restrictive access that accomplishes this objective?

A.
public
B.
private
C.
protected
D.
transient

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

Access modifiers dictate which classes, not which instances, may access features.

Methods and variables are collectively known as members. Method and variable members are given access control in exactly the same way.

private makes a member accessible only from within its own class

protected makes a member accessible only to classes in the same package or subclass of the class

default access is very similar to protected (make sure you spot the difference) default access makes a member accessible only to classes in the same package.

public means that all other classes regardless of the package that they belong to, can access the member (assuming the class itself is visible)

final makes it impossible to extend a class, when applied to a method it prevents a method from being overridden in a subclass, when applied to a variable it makes it impossible to reinitialise a variable once it has been initialised

abstract declares a method that has not been implemented.

transient indicates that a variable is not part of the persistent state of an object.

volatile indicates that a thread must reconcile its working copy of the field with the master copy every time it accesses the variable.

After examining the above it should be obvious that the access modifier that provides the most restrictions for methods to be accessed from the subclasses of the class from another package is C - protected. A is also a contender but C is more restrictive, B would be the answer if the constraint was the "same package" instead of "any package" in other words the subclasses clause in the question eliminates default.

Learn more problems on : Declarations and Access Control

Discuss about this problem : Discuss in Forum


3.

interface Base 
{
    boolean m1 ();
    byte m2(short s);
}
which two code fragments will compile?
  1. interface Base2 implements Base {}
  2. abstract class Class2 extends Base
    { public boolean m1(){ return true; }}
  3. abstract class Class2 implements Base {}
  4. abstract class Class2 implements Base
    { public boolean m1(){ return (7 > 4); }}
  5. abstract class Class2 implements Base
    { protected boolean m1(){ return (5 > 7) }}

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

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

(3) is correct because an abstract class doesn't have to implement any or all of its interface's methods. (4) is correct because the method is correctly implemented ((7 > 4) is a boolean).

(1) is incorrect because interfaces don't implement anything. (2) is incorrect because classes don't extend interfaces. (5) is incorrect because interface methods are implicitly public, so the methods being implemented must be public.

Learn more problems on : Declarations and Access Control

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


6.

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


7.

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

Your Answer: Option (Not Answered)

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

Learn more problems on : Inner Classes

Discuss about this problem : Discuss in Forum


8.

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


9.

Which three statements are true?

  1. Assertion checking is typically enabled when a program is deployed.
  2. It is never appropriate to write code to handle failure of an assert statement.
  3. Assertion checking is typically enabled during program development and testing.
  4. Assertion checking can be selectively enabled or disabled on a per-package basis, but not on a per-class basis.
  5. Assertion checking can be selectively enabled or disabled on both a per-package basis and a per-class basis.

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

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

(1) is wrong. It's just not true.

(2) is correct. You're never supposed to handle an assertion failure.

(3) is correct. Assertions let you test your assumptions during development, but the assertion code—in effect—evaporates when the program is deployed, leaving behind no overhead or debugging code to track down and remove.

(4) is wrong. See the explanation for (5) below.

(5) is correct. Assertion checking can be selectively enabled or disabled on a per-package basis. Note that the package default assertion status determines the assertion status for classes initialized in the future that belong to the named package or any of its "subpackages".

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.

Learn more problems on : Assertions

Discuss about this problem : Discuss in Forum


10.

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.

Your Answer: Option (Not Answered)

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

Learn more problems on : Language Fundamentals

Discuss about this problem : Discuss in Forum


11.

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.

Your Answer: Option (Not Answered)

Correct Answer: Option A

Explanation:

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

Learn more problems on : Flow Control

Discuss about this problem : Discuss in Forum


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};

Your Answer: Option (Not Answered)

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

Learn more problems on : Language Fundamentals

Discuss about this problem : Discuss in Forum


13.

What will be the output of the program?

class Q207 
{ 
    public static void main(String[] args) 
    {
        int i1 = 5; 
        int i2 = 6; 
        String s1 = "7"; 
        System.out.println(i1 + i2 + s1); /* Line 8 */
    } 
}

A.
18
B.
117
C.
567
D.
Compiler error

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

This question is about the + (plus) operator and the overriden + (string cocatanation) operator. The rules that apply when you have a mixed expression of numbers and strings are:

If either operand is a String, the + operator concatenates the operands.

If both operands are numeric, the + operator adds the operands.

The expression on line 6 above can be read as "Add the values i1 and i2 together, then take the sum and convert it to a string and concatenate it with the String from the variable s1". In code, the compiler probably interprets the expression on line 8 above as:

System.out.println( new StringBuffer() 
    .append(new Integer(i1 + i2).toString()) 
    .append(s1) 
    .toString() ); 

Learn more problems on : Java.lang Class

Discuss about this problem : Discuss in Forum


14.

What will be the output of the program?

public class Test 
{ 
    public static void main(String[] args) 
    {
        final StringBuffer a = new StringBuffer(); 
        final StringBuffer b = new StringBuffer(); 

        new Thread() 
        { 
            public void run() 
            {
                System.out.print(a.append("A")); 
                synchronized(b) 
                { 
                    System.out.print(b.append("B")); 
                } 
            } 
        }.start(); 
            
        new Thread() 
        {
            public void run() 
            {
                System.out.print(b.append("C")); 
                synchronized(a) 
                {
                    System.out.print(a.append("D")); 
                } 
            } 
        }.start(); 
    } 
}

A.
ACCBAD
B.
ABBCAD
C.
CDDACB
D.
Indeterminate output

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

It gives different output while executing the same compiled code at different times.

C:\>javac Test.java
C:\>java Test
ABBCAD
C:\>java Test
ACADCB
C:\>java Test
ACBCBAD
C:\>java Test
ABBCAD
C:\>java Test
ACBCBAD
C:\>java Test
ACBCBAD
C:\>java Test
ABBCAD

Learn more problems on : Java.lang Class

Discuss about this problem : Discuss in Forum


15.

What will be the output of the program?

class Tree { } 
class Pine extends Tree { } 
class Oak extends Tree { } 
public class Forest1 
{ 
    public static void main (String [] args)
    { 
        Tree tree = new Pine(); 
        if( tree instanceof Pine ) 
            System.out.println ("Pine"); 
        else if( tree instanceof Tree ) 
            System.out.println ("Tree"); 
        else if( tree instanceof Oak ) 
            System.out.println ( "Oak" ); 
        else 
            System.out.println ("Oops "); 
    } 
}

A.
Pine
B.
Tree
C.
Forest
D.
Oops

Your Answer: Option (Not Answered)

Correct Answer: Option A

Explanation:

The program prints "Pine".

Learn more problems on : Java.lang Class

Discuss about this problem : Discuss in Forum


16.

What will be the output of the program?

try 
{
    Float f1 = new Float("3.0");
    int x = f1.intValue();
    byte b = f1.byteValue();
    double d = f1.doubleValue();
    System.out.println(x + b + d);
}
catch (NumberFormatException e) /* Line 9 */
{
    System.out.println("bad number"); /* Line 11 */
}

A.
9.0
B.
bad number
C.
Compilation fails on line 9.
D.
Compilation fails on line 11.

Your Answer: Option (Not Answered)

Correct Answer: Option A

Explanation:

The xxxValue() methods convert any numeric wrapper object's value to any primitive type. When narrowing is necessary, significant bits are dropped and the results are difficult to calculate.

Learn more problems on : Java.lang Class

Discuss about this problem : Discuss in Forum


17.

Which of the following will produce an answer that is closest in value to a double, d, while not being greater than d?

A.
(int)Math.min(d);
B.
(int)Math.max(d);
C.
(int)Math.abs(d);
D.
(int)Math.floor(d);

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

The casting to an int is a smokescreen. Use a process of elimination to answer this question:

Option D is the correct answer, it is syntathecially correct and will consistently return a value less than d.

Option A and B are wrong because both the min() and max() methods require 2 arguments whereas here they are passed only one parameter.

Option C is wrong because it could return a value greater than d (if d was negative).

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 SyncTest 
{
    public static void main (String [] args) 
    {
        Thread t = new Thread() 
        {
            Foo f = new Foo();
            public void run() 
            {
                f.increase(20);
            }
        };
    t.start();
    }
}
class Foo 
{
    private int data = 23;
    public void increase(int amt) 
    {
        int x = data;
        data = x + amt;
    }
}
and assuming that data must be protected from corruption, what—if anything—can you add to the preceding code to ensure the integrity of data?

A.
Synchronize the run method.
B.
Wrap a synchronize(this) around the call to f.increase().
C.
The existing code will cause a runtime exception.
D.
Synchronize the increase() method

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

Option D is correct because synchronizing the code that actually does the increase will protect the code from being accessed by more than one thread at a time.

Option A is incorrect because synchronizing the run() method would stop other threads from running the run() method (a bad idea) but still would not prevent other threads with other runnables from accessing the increase() method.

Option B is incorrect for virtually the same reason as A—synchronizing the code that calls the increase() method does not prevent other code from calling the increase() method.

Learn more problems on : Threads

Discuss about this problem : Discuss in Forum


19.

class Test 
{
    public static void main(String [] args) 
    {
        printAll(args);
    }

    public static void printAll(String[] lines) 
    {
        for(int i = 0; i < lines.length; i++)
        {
            System.out.println(lines[i]);
            Thread.currentThread().sleep(1000);
        }
    }
}
the static method Thread.currentThread() returns a reference to the currently executing Thread object. What is the result of this code?

A.
Each String in the array lines will output, with a 1-second pause.
B.
Each String in the array lines will output, with no pause in between because this method is not executed in a Thread.
C.
Each String in the array lines will output, and there is no guarantee there will be a pause because currentThread() may not retrieve this thread.
D.
This code will not compile.

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

D. The sleep() method must be enclosed in a try/catch block, or the method printAll() must declare it throws the InterruptedException.

A is incorrect, but it would be correct if the InterruptedException was dealt with.

B is incorrect, but it would still be incorrect if the InterruptedException was dealt with because all Java code, including the main() method, runs in threads.

C is incorrect. The sleep() method is static, so even if it is called on an instance, it still always affects the currently executing thread.

Learn more problems on : Threads

Discuss about this problem : Discuss in Forum


20.

Which statement is true?

A.
catch(X x) can catch subclasses of X where X is a subclass of Exception.
B.
The Error class is a RuntimeException.
C.
Any statement that can throw an Error must be enclosed in a try block.
D.
Any statement that can throw an Exception must be enclosed in a try block.

Your Answer: Option (Not Answered)

Correct Answer: Option A

Explanation:

Option A is correct. If the class specified in the catch clause does have subclasses, any exception object that subclasses the specified class will be caught as well.

Option B is wrong. The error class is a subclass of Throwable and not Runtime Exception.

Option C is wrong. You do not catch this class of error.

Option D is wrong. An exception can be thrown to the next method higher up the call stack.

Learn more problems on : Exceptions

Discuss about this problem : Discuss in Forum


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