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.

Which collection class allows you to grow or shrink its size and provides indexed access to its elements, but whose methods are not synchronized?

A.
java.util.HashSet
B.
java.util.LinkedHashSet
C.
java.util.List
D.
java.util.ArrayList

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

All of the collection classes allow you to grow or shrink the size of your collection. ArrayList provides an index to its elements. The newer collection classes tend not to have synchronized methods. Vector is an older implementation of ArrayList functionality and has synchronized methods; it is slower than ArrayList.

Learn more problems on : Objects and Collections

Discuss about this problem : Discuss in Forum


2.

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.

Your Answer: Option (Not Answered)

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

Learn more problems on : Flow Control

Discuss about this problem : Discuss in Forum


3.

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

Your Answer: Option (Not Answered)

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

Learn more problems on : Flow Control

Discuss about this problem : Discuss in Forum


4.

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


5.

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


6.

What will be the output of the program?

public class ObjComp 
{
    public static void main(String [] args ) 
    {
        int result = 0;
        ObjComp oc = new ObjComp();
        Object o = oc;

        if (o == oc)  
            result = 1;
        if (o != oc)  
            result = result + 10;
        if (o.equals(oc) )  
            result = result + 100;
        if (oc.equals(o) )  
            result = result + 1000;

        System.out.println("result = " + result);
    }
}

A.
1
B.
10
C.
101
D.
1101

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

Even though o and oc are reference variables of different types, they are both referring to the same object. This means that == will resolve to true and that the default equals() method will also resolve to true.

Learn more problems on : Java.lang Class

Discuss about this problem : Discuss in Forum


7.

What will be the output of the program?

int i = 1, j = 10; 
do 
{
    if(i++ > --j) /* Line 4 */
    {
        continue; 
    } 
} while (i < 5); 
System.out.println("i = " + i + "and j = " + j); /* Line 9 */

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

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

This question is not testing your knowledge of the continue statement. It is testing your knowledge of the order of evaluation of operands. Basically the prefix and postfix unary operators have a higher order of evaluation than the relational operators. So on line 4 the variable i is incremented and the variable j is decremented before the greater than comparison is made. As the loop executes the comparison on line 4 will be:

if(i > j)

if(2 > 9)

if(3 > 8)

if(4 > 7)

if(5 > 6) at this point i is not less than 5, therefore the loop terminates and line 9 outputs the values of i and j as 5 and 6 respectively.

The continue statement never gets to execute because i never reaches a value that is greater than j.

Learn more problems on : Java.lang Class

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.

Which method must be defined by a class implementing the java.lang.Runnable interface?

A.
void run()
B.
public void run()
C.
public void start()
D.
void run(int priority)

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

Option B is correct because in an interface all methods are abstract by default therefore they must be overridden by the implementing class. The Runnable interface only contains 1 method, the void run() method therefore it must be implemented.

Option A and D are incorrect because they are narrowing the access privileges i.e. package(default) access is narrower than public access.

Option C is not method in the Runnable interface therefore it is incorrect.

Learn more problems on : Threads

Discuss about this problem : Discuss in Forum


10.

What will be the output of the program?

class MyThread extends Thread 
{ 
    MyThread() {} 
    MyThread(Runnable r) {super(r); } 
    public void run() 
    { 
        System.out.print("Inside Thread ");
    } 
} 
class MyRunnable implements Runnable 
{ 
    public void run() 
    { 
        System.out.print(" Inside Runnable"); 
    } 
} 
class Test 
{  
    public static void main(String[] args) 
    { 
        new MyThread().start(); 
        new MyThread(new MyRunnable()).start(); 
    } 
}

A.
Prints "Inside Thread Inside Thread"
B.
Prints "Inside Thread Inside Runnable"
C.
Does not compile
D.
Throws exception at runtime

Your Answer: Option (Not Answered)

Correct Answer: Option A

Explanation:

If a Runnable object is passed to the Thread constructor, then the run method of the Thread class will invoke the run method of the Runnable object.

In this case, however, the run method in the Thread class is overridden by the run method in MyThread class. Therefore the run() method in MyRunnable is never invoked.

Both times, the run() method in MyThread is invoked instead.

Learn more problems on : Threads

Discuss about this problem : Discuss in Forum


11.

Which statement is true given the following?

Double d = Math.random();

A.
0.0 < d <= 1.0
B.
0.0 <= d < 1.0
C.
Compilation fail
D.
Cannot say.

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

The Math.random() method returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0

Learn more problems on : Java.lang Class

Discuss about this problem : Discuss in Forum


12.

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


13.

What will be the output of the program?

public class Test 
{ 
    private static int[] x; 
    public static void main(String[] args) 
    { 
        System.out.println(x[0]); 
    } 
}

A.
B.
null
C.
Compile Error
D.
NullPointerException at runtime

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

In the above code the array reference variable x has been declared but it has not been instantiated i.e. the new statement is missing, for example:

private static int[]x = new int[5];

private static int[x] declares a static i.e. class level array.

the "new" keyword is the word that actually creates said array.

int[5] in association with the new sets the size of the array. so since the above code contains no new or size decalarations when you try and access x[0] you are trying to access a member of an array that has been declared but not intialized hence you get a NullPointerException at runtime.

Learn more problems on : Objects and Collections

Discuss about this problem : Discuss in Forum


14.

What will be the output of the program?

public static void main(String[] args) 
{
    Object obj = new Object() 
    {
        public int hashCode() 
        {
            return 42;
        }
    }; 
    System.out.println(obj.hashCode()); 
}

A.
42
B.
Runtime Exception
C.
Compile Error at line 2
D.
Compile Error at line 5

Your Answer: Option (Not Answered)

Correct Answer: Option A

Explanation:

This code is an example of an anonymous inner class. They can be declared to extend another class or implement a single interface. Since they have no name you can not use the "new" keyword on them.

In this case the annoynous class is extending the Object class. Within the {} you place the methods you want for that class. After this class has been declared its methods can be used by that object in the usual way e.g. objectname.annoymousClassMethod()

Learn more problems on : Objects and Collections

Discuss about this problem : Discuss in Forum


15.

Which two statements are true for any concrete class implementing the java.lang.Runnable interface?

  1. You can extend the Runnable interface as long as you override the public run() method.
  2. The class must contain a method called run() from which all code for that thread will be initiated.
  3. The class must contain an empty public void method named run().
  4. The class must contain a public void method named runnable().
  5. The class definition must include the words implements Threads and contain a method called run().
  6. The mandatory method must be public, with a return type of void, must be called run(), and cannot take any arguments.

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

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

(2) and (6). When a thread's run() method completes, the thread will die. The run() method must be declared public void and not take any arguments.

(1) is incorrect because classes can never extend interfaces. (3) is incorrect because the run() method is typically not empty; if it were, the thread would do nothing. (4) is incorrect because the mandatory method is run(). (5) is incorrect because the class implements Runnable.

Learn more problems on : Declarations and Access Control

Discuss about this problem : Discuss in Forum


16.

Which three statements are true?

  1. The default constructor initialises method variables.
  2. The default constructor has the same access as its class.
  3. The default constructor invokes the no-arg constructor of the superclass.
  4. If a class lacks a no-arg constructor, the compiler always creates a default constructor.
  5. The compiler creates a default constructor only when there are no other constructors for the class.

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

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

(2) sounds correct as in the example below

class CoffeeCup { 
    private int innerCoffee; 
    public CoffeeCup() { 
   } 
  
    public void add(int amount) { 
    innerCoffee += amount; 
   } 
   //... 
 } 
The compiler gives default constructors the same access level as their class. In the example above, class CoffeeCup is public, so the default constructor is public. If CoffeeCup had been given package access, the default constructor would be given package access as well.

(3) is correct. The Java compiler generates at least one instance initialisation method for every class it compiles. In the Java class file, the instance initialisation method is named "<init>." For each constructor in the source code of a class, the Java compiler generates one <init>() method. If the class declares no constructors explicitly, the compiler generates a default no-arg constructor that just invokes the superclass's no-arg constructor. As with any other constructor, the compiler creates an <init>() method in the class file that corresponds to this default constructor.

(5) is correct. The compiler creates a default constructor if you do not declare any constructors in your class.

Learn more problems on : Declarations and Access Control

Discuss about this problem : Discuss in Forum


17.

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


18.

What will be the output of the program?

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

    void start() 
    {
        int a = 3;
        int b = 4;
        System.out.print(" " + 7 + 2 + " ");
        System.out.print(a + b);
        System.out.print(" " + a + b + " ");
        System.out.print(foo() + a + b + " ");
        System.out.println(a + b + foo());
    }

    String foo() 
    {
        return "foo";
    }
}

A.
9 7 7 foo 7 7foo
B.
72 34 34 foo34 34foo
C.
9 7 7 foo34 34foo
D.
72 7 34 foo34 7foo

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

Because all of these expressions use the + operator, there is no precedence to worry about and all of the expressions will be evaluated from left to right. If either operand being evaluated is a String, the + operator will concatenate the two operands; if both operands are numeric, the + operator will add the two operands.

Learn more problems on : Operators and Assignments

Discuss about this problem : Discuss in Forum


19.

What will be the output of the program?

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

    void start() 
    {
        boolean b1 = false;
        boolean b2 = fix(b1);
        System.out.println(b1 + " " + b2);
    }

    boolean fix(boolean b1) 
    {
        b1 = true;
        return b1;
    }
}

A.
true true
B.
false true
C.
true false
D.
false false

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

The boolean b1 in the fix() method is a different boolean than the b1 in the start() method. The b1 in the start() method is not updated by the fix() method.

Learn more problems on : Operators and Assignments

Discuss about this problem : Discuss in Forum


20.

You want a class to have access to members of another class in the same package. Which is the most restrictive access that accomplishes this objective?

A.
public
B.
private
C.
protected
D.
default access

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

The only two real contenders are C and D. Protected access Option C makes a member accessible only to classes in the same package or subclass of the class. While default access Option D makes a member accessible only to classes in the same package.

Learn more problems on : Declarations and Access Control

Discuss about this problem : Discuss in Forum


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