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.

Which class or interface defines the wait(), notify(),and notifyAll() methods?

A.
Object
B.
Thread
C.
Runnable
D.
Class

Your Answer: Option (Not Answered)

Correct Answer: Option A

Explanation:

The Object class defines these thread-specific methods.

Option B, C, and D are incorrect because they do not define these methods. And yes, the Java API does define a class called Class, though you do not need to know it for the exam.

Learn more problems on : Threads

Discuss about this problem : Discuss in Forum


2.

What will be the output of the program?

int I = 0;
    outer:
    while (true) 
    {
        I++;
        inner:
        for (int j = 0; j < 10; j++) 
        {
            I += j;
            if (j == 3)
                continue inner;
            break outer;
        }
        continue outer;
    }
System.out.println(I);

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

Your Answer: Option (Not Answered)

Correct Answer: Option A

Explanation:

The program flows as follows: I will be incremented after the while loop is entered, then I will be incremented (by zero) when the for loop is entered. The if statement evaluates to false, and the continue statement is never reached. The break statement tells the JVM to break out of the outer loop, at which point I is printed and the fragment is done.

Learn more problems on : Flow Control

Discuss about this problem : Discuss in Forum


3.

What will be the output of the program?

int i = 1, j = 10; 
do 
{
    if(i > j) 
    {
        break; 
    } 
    j--; 
} while (++i < 5); 
System.out.println("i = " + i + " and j = " + j);

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

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

This loop is a do-while loop, which always executes the code block within the block at least once, due to the testing condition being at the end of the loop, rather than at the beginning. This particular loop is exited prematurely if i becomes greater than j.

The order is, test i against j, if bigger, it breaks from the loop, decrements j by one, and then tests the loop condition, where a pre-incremented by one i is tested for being lower than 5. The test is at the end of the loop, so i can reach the value of 5 before it fails. So it goes, start:

1, 10

2, 9

3, 8

4, 7

5, 6 loop condition fails.

Learn more problems on : Flow Control

Discuss about this problem : Discuss in Forum


4.

switch(x) 
{ 
    default:  
        System.out.println("Hello"); 
}
Which two are acceptable types for x?
  1. byte
  2. long
  3. char
  4. float
  5. Short
  6. Long

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

Your Answer: Option (Not Answered)

Correct Answer: Option A

Explanation:

Switch statements are based on integer expressions and since both bytes and chars can implicitly be widened to an integer, these can also be used. Also shorts can be used. Short and Long are wrapper classes and reference types can not be used as variables.

Learn more problems on : Flow Control

Discuss about this problem : Discuss in Forum


5.

Which of the following are valid calls to Math.max?

  1. Math.max(1,4)
  2. Math.max(2.3, 5)
  3. Math.max(1, 3, 5, 7)
  4. Math.max(-1.5, -2.8f)

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

Your Answer: Option (Not Answered)

Correct Answer: Option A

Explanation:

(1), (2), and (4) are correct. The max() method is overloaded to take two arguments of type int, long, float, or double.

(3) is incorrect because the max() method only takes two arguments.

Learn more problems on : Java.lang Class

Discuss about this problem : Discuss in Forum


6.

What will be the output of the program?

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

    void start() 
    {
        long [] a1 = {3,4,5};
        long [] a2 = fix(a1);
        System.out.print(a1[0] + a1[1] + a1[2] + " ");
        System.out.println(a2[0] + a2[1] + a2[2]);
    }

    long [] fix(long [] a3) 
    {
        a3[1] = 7;
        return a3;
    }
}

A.
12 15
B.
15 15
C.
3 4 5 3 7 5
D.
3 7 5 3 7 5

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

Output: 15 15

The reference variables a1 and a3 refer to the same long array object. When the [1] element is updated in the fix() method, it is updating the array referred to by a1. The reference variable a2 refers to the same array object.

So Output: 3+7+5+" "3+7+5

Output: 15 15 Because Numeric values will be added

Learn more problems on : Operators and Assignments

Discuss about this problem : Discuss in Forum


7.

What will be the output of the program?

class Test 
{
    public static void main(String [] args) 
    {
        int x=20;
        String sup = (x < 15) ? "small" : (x < 22)? "tiny" : "huge";
        System.out.println(sup);
    }
}

A.
small
B.
tiny
C.
huge
D.
Compilation fails

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

This is an example of a nested ternary operator. The second evaluation (x < 22) is true, so the "tiny" value is assigned to sup.

Learn more problems on : Operators and Assignments

Discuss about this problem : Discuss in Forum


8.

System.out.print("Start ");
try 
{
    System.out.print("Hello world");
    throw new FileNotFoundException();
}
System.out.print(" Catch Here "); /* Line 7 */
catch(EOFException e) 
{
    System.out.print("End of file exception");
}
catch(FileNotFoundException e) 
{
    System.out.print("File not found");
}
and given that EOFException and FileNotFoundException are both subclasses of IOException, and further assuming this block of code is placed into a class, which statement is most true concerning this code?

A.
The code will not compile.
B.
Code output: Start Hello world File Not Found.
C.
Code output: Start Hello world End of file exception.
D.
Code output: Start Hello world Catch Here File not found.

Your Answer: Option (Not Answered)

Correct Answer: Option A

Explanation:

Line 7 will cause a compiler error. The only legal statements after try blocks are either catch or finally statements.

Option B, C, and D are incorrect based on the program logic described above. If line 7 was removed, the code would compile and the correct answer would be Option B.

Learn more problems on : Exceptions

Discuss about this problem : Discuss in Forum


9.

Given a method in a protected class, what access modifier do you use to restrict access to that method to only the other members of the same class?

A.
final
B.
static
C.
private
D.
protected
E.
volatile

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

The private access modifier limits access to members of the same class.

Option A, B, D, and E are wrong because protected are the wrong access modifiers, and final, static, and volatile are modifiers but not access modifiers.

Learn more problems on : Declarations and Access Control

Discuss about this problem : Discuss in Forum


10.

Which of the following is/are legal method declarations?

  1. protected abstract void m1();
  2. static final void m1(){}
  3. synchronized public final void m1() {}
  4. private native void m1();

A.
1 and 3
B.
2 and 4
C.
1 only
D.
All of them are legal declarations.

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

All the given statements are legal declarations.

Learn more problems on : Declarations and Access Control

Discuss about this problem : Discuss in Forum


11.

What will be the output of the program?

class MyThread extends Thread 
{
    public static void main(String [] args) 
    {
        MyThread t = new MyThread(); /* Line 5 */
        t.run();  /* Line 6 */
    }

    public void run() 
    {
        for(int i=1; i < 3; ++i) 
        {
            System.out.print(i + "..");
        }
    }
}

A.
This code will not compile due to line 5.
B.
This code will not compile due to line 6.
C.
1..2..
D.
1..2..3..

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

Line 6 calls the run() method, so the run() method executes as a normal method should and it prints "1..2.."

A is incorrect because line 5 is the proper way to create an object.

B is incorrect because it is legal to call the run() method, even though this will not start a true thread of execution. The code after line 6 will not execute until the run() method is complete.

D is incorrect because the for loop only does two iterations.

Learn more problems on : Threads

Discuss about this problem : Discuss in Forum


12.

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


13.

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


14.

Which statement is true?

A.
Calling Runtime.gc() will cause eligible objects to be garbage collected.
B.
The garbage collector uses a mark and sweep algorithm.
C.
If an object can be accessed from a live thread, it can't be garbage collected.
D.
If object 1 refers to object 2, then object 2 can't be garbage collected.

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

This is a great way to think about when objects can be garbage collected.

Option A and B assume guarantees that the garbage collector never makes.

Option D is wrong because of the now famous islands of isolation scenario.

Learn more problems on : Garbage Collections

Discuss about this problem : Discuss in Forum


15.

public class Test 
{ 
    public void foo() 
    {
        assert false; /* Line 5 */
        assert false; /* Line 6 */
    } 
    public void bar()
    {
        while(true)
        {
            assert false; /* Line 12 */
        } 
        assert false;  /* Line 14 */
    } 
}
What causes compilation to fail?

A.
Line 5
B.
Line 6
C.
Line 12
D.
Line 14

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

Option D is correct. Compilation fails because of an unreachable statement at line 14. It is a compile-time error if a statement cannot be executed because it is unreachable. The question is now, why is line 20 unreachable? If it is because of the assert then surely line 6 would also be unreachable. The answer must be something other than assert.

Examine the following:

A while statement can complete normally if and only if at least one of the following is true:

- The while statement is reachable and the condition expression is not a constant expression with value true.

-There is a reachable break statement that exits the while statement.

The while statement at line 11 is infinite and there is no break statement therefore line 14 is unreachable. You can test this with the following code:

public class Test80 
{ 
    public void foo() 
    {
        assert false; 
        assert false; 
    } 
    public void bar()
    {
        while(true)
        {
            assert false; 
            break; 
        } 
        assert false;  
    } 
}

Learn more problems on : Assertions

Discuss about this problem : Discuss in Forum


16.

What will be the output of the program?

class Base
{ 
    Base()
    {
        System.out.print("Base");
    }
} 
public class Alpha extends Base
{ 
    public static void main(String[] args)
    { 
        new Alpha(); /* Line 12 */
        new Base(); /* Line 13 */
    } 
}

A.
Base
B.
BaseBase
C.
Compilation fails
D.
The code runs with no output

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

Option B is correct. It would be correct if the code had compiled, and the subclass Alpha had been saved in its own file. In this case Java supplies an implicit call from the sub-class constructor to the no-args constructor of the super-class therefore line 12 causes Base to be output. Line 13 also causes Base to be output.

Option A is wrong. It would be correct if either the main class or the subclass had not been instantiated.

Option C is wrong. The code compiles.

Option D is wrong. There is output.

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 BoolTest 
{
    public static void main(String [] args) 
    {
        int result = 0;

        Boolean b1 = new Boolean("TRUE");
        Boolean b2 = new Boolean("true");
        Boolean b3 = new Boolean("tRuE");
        Boolean b4 = new Boolean("false");

        if (b1 == b2)  /* Line 10 */
            result = 1;
        if (b1.equals(b2) ) /* Line 12 */
            result = result + 10;
        if (b2 == b4)  /* Line 14 */
            result = result + 100;
        if (b2.equals(b4) ) /* Line 16 */
            result = result + 1000;
        if (b2.equals(b3) ) /* Line 18 */
            result = result + 10000;

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

A.
0
B.
1
C.
10
D.
10010

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

Line 10 fails because b1 and b2 are two different objects. Lines 12 and 18 succeed because the Boolean String constructors are case insensitive. Lines 14 and 16 fail because true is not equal to false.

Learn more problems on : Java.lang Class

Discuss about this problem : Discuss in Forum


18.

What will be the output of the program?

String a = "newspaper";
a = a.substring(5,7);
char b = a.charAt(1);
a = a + b;
System.out.println(a);

A.
apa
B.
app
C.
apea
D.
apep

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

Both substring() and charAt() methods are indexed with a zero-base, and substring() returns a String of length arg2 - arg1.

Learn more problems on : Java.lang Class

Discuss about this problem : Discuss in Forum


19.

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


20.

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


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