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.

x = 0;
if (x1.hashCode() != x2.hashCode() )  x = x + 1;
if (x3.equals(x4) )  x = x + 10;
if (!x5.equals(x6) ) x = x + 100;
if (x7.hashCode() == x8.hashCode() )  x = x + 1000;
System.out.println("x = " + x);
and assuming that the equals() and hashCode() methods are properly implemented, if the output is "x = 1111", which of the following statements will always be true?

A.
x2.equals(x1)
B.
x3.hashCode() == x4.hashCode()
C.
x5.hashCode() != x6.hashCode()
D.
x8.equals(x7)

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

By contract, if two objects are equivalent according to the equals() method, then the hashCode() method must evaluate them to be ==.

Option A is incorrect because if the hashCode() values are not equal, the two objects must not be equal.

Option C is incorrect because if equals() is not true there is no guarantee of any result from hashCode().

Option D is incorrect because hashCode() will often return == even if the two objects do not evaluate to equals() being true.

Learn more problems on : Objects and Collections

Discuss about this problem : Discuss in Forum

2.

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

3.

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

4.

What will be the output of the program?

public class WrapTest 
{
    public static void main(String [] args) 
    {
        int result = 0;
        short s = 42;
        Long x = new Long("42");
        Long y = new Long(42);
        Short z = new Short("42");
        Short x2 = new Short(s);
        Integer y2 = new Integer("42");
        Integer z2 = new Integer(42);

        if (x == y) /* Line 13 */
            result = 1;
        if (x.equals(y) ) /* Line 15 */
            result = result + 10;
        if (x.equals(z) ) /* Line 17 */
            result = result + 100;
        if (x.equals(x2) ) /* Line 19 */
            result = result + 1000;
        if (x.equals(z2) ) /* Line 21 */
            result = result + 10000;

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

A.
result = 1
B.
result = 10
C.
result = 11
D.
result = 11010

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

Line 13 fails because == compares reference values, not object values. Line 15 succeeds because both String and primitive wrapper constructors resolve to the same value (except for the Character wrapper). Lines 17, 19, and 21 fail because the equals() method fails if the object classes being compared are different and not in the same tree hierarchy.

Learn more problems on : Java.lang Class

Discuss about this problem : Discuss in Forum

5.

What will be the output of the program?

public class ExamQuestion7 
{  
    static int j; 
    static void methodA(int i)
    {
        boolean b; 
        do
        { 
            b = i<10 | methodB(4); /* Line 9 */
            b = i<10 || methodB(8);  /* Line 10 */
        }while (!b); 
    } 
    static boolean methodB(int i)
    {
        j += i; 
        return true; 
    } 
    public static void main(String[] args)
    {
        methodA(0); 
        System.out.println( "j = " + j ); 
    } 
}

A.
j = 0
B.
j = 4
C.
j = 8
D.
The code will run with no output

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

The lines to watch here are lines 9 & 10. Line 9 features the non-shortcut version of the OR operator so both of its operands will be evaluated and therefore methodB(4) is executed.

However line 10 has the shortcut version of the OR operator and if the 1st of its operands evaluates to true (which in this case is true), then the 2nd operand isn't evaluated, so methodB(8) never gets called.

The loop is only executed once, b is initialized to false and is assigned true on line 9. Thus j = 4.

Learn more problems on : Java.lang Class

Discuss about this problem : Discuss in Forum

6.

Which statement is true?

A.
A try statement must have at least one corresponding catch block.
B.
Multiple catch statements can catch the same class of exception more than once.
C.
An Error that might be thrown in a method must be declared as thrown by that method, or be handled within that method.
D.
Except in case of VM shutdown, if a try block starts to execute, a corresponding finally block will always start to execute.

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

A is wrong. A try statement can exist without catch, but it must have a finally statement.

B is wrong. A try statement executes a block. If a value is thrown and the try statement has one or more catch clauses that can catch it, then control will be transferred to the first such catch clause. If that catch block completes normally, then the try statement completes normally.

C is wrong. Exceptions of type Error and RuntimeException do not have to be caught, only checked exceptions (java.lang.Exception) have to be caught. However, speaking of Exceptions, Exceptions do not have to be handled in the same method as the throw statement. They can be passed to another method.

If you put a finally block after a try and its associated catch blocks, then once execution enters the try block, the code in that finally block will definitely be executed except in the following circumstances:

  1. An exception arising in the finally block itself.
  2. The death of the thread.
  3. The use of System.exit()
  4. Turning off the power to the CPU.
I suppose the last three could be classified as VM shutdown.

Learn more problems on : Exceptions

Discuss about this problem : Discuss in Forum

7.

Which four can be thrown using the throw statement?

  1. Error
  2. Event
  3. Object
  4. Throwable
  5. Exception
  6. RuntimeException

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

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

The (1), (4), (5) and (6) are the only four that can be thrown.

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch.

The Throwable class is the superclass of all errors and exceptions in the Java language.

The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch (checked exceptions)

RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine.

Learn more problems on : Exceptions

Discuss about this problem : Discuss in Forum

8.

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

9.

public class ExceptionTest 
{ 
    class TestException extends Exception {} 
    public void runTest() throws TestException {} 
    public void test() /* Point X */ 
    { 
        runTest(); 
    } 
}
At Point X on line 5, which code is necessary to make the code compile?

A.
No code is necessary.
B.
throws Exception
C.
catch ( Exception e )
D.
throws RuntimeException

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

Option B is correct. This works because it DOES throw an exception if an error occurs.

Option A is wrong. If you compile the code as given the compiler will complain:

"unreported exception must be caught or declared to be thrown" The class extends Exception so we are forced to test for exceptions.

Option C is wrong. The catch statement belongs in a method body not a method specification.

Option D is wrong. TestException is a subclass of Exception therefore the test method, in this example, must throw TestException or some other class further up the Exception tree. Throwing RuntimeException is just not on as this belongs in the java.lang.RuntimeException branch (it is not a superclass of TestException). The compiler complains with the same error as in A above.

Learn more problems on : Exceptions

Discuss about this problem : Discuss in Forum

10.

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

11.

Which two are equal?

  1. 32/4
  2. (8 >> 2) << 4
  3. 2^5
  4. 128 >>> 2
  5. 2 >> 5

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

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

(2) and (4) are correct. (2) and (4) both evaluate to 32. (2) is shifting bits right then left using the signed bit shifters >> and <<. (4) is shifting bits using the unsigned operator >>>, but since the beginning number is positive the sign is maintained.

(1) evaluates to 8, (3) looks like 2 to the 5th power, but ^ is the Exclusive OR operator so (3) evaluates to 7. (5) evaluates to 0 (2 >> 5 is not 2 to the 5th).

Learn more problems on : Operators and Assignments

Discuss about this problem : Discuss in Forum

12.

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

13.

Which three are valid declarations of a char?

  1. char c1 = 064770;
  2. char c2 = 'face';
  3. char c3 = 0xbeef;
  4. char c4 = \u0022;
  5. char c5 = '\iface';
  6. char c6 = '\uface';

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

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

(1), (3), and (6) are correct. char c1 = 064770; is an octal representation of the integer value 27128, which is legal because it fits into an unsigned 16-bit integer. char c3 = 0xbeef; is a hexadecimal representation of the integer value 48879, which fits into an unsigned 16-bit integer. char c6 = '\uface'; is a Unicode representation of a character.

char c2 = 'face'; is wrong because you can't put more than one character in a char literal. The only other acceptable char literal that can go between single quotes is a Unicode value, and Unicode literals must always start with a '\u'.

char c4 = \u0022; is wrong because the single quotes are missing.

char c5 = '\iface'; is wrong because it appears to be a Unicode representation (notice the backslash), but starts with '\i' rather than '\u'.

Learn more problems on : Language Fundamentals

Discuss about this problem : Discuss in Forum

14.

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

15.

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

16.

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

17.

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

18.

Assume the following method is properly synchronized and called from a thread A on an object B:

wait(2000);

After calling this method, when will the thread A become a candidate to get another turn at the CPU?

A.
After thread A is notified, or after two seconds.
B.
After the lock on B is released, or after two seconds.
C.
Two seconds after thread A is notified.
D.
Two seconds after lock B is released.

Your Answer: Option (Not Answered)

Correct Answer: Option A

Explanation:

Option A. Either of the two events (notification or wait time expiration) will make the thread become a candidate for running again.

Option B is incorrect because a waiting thread will not return to runnable when the lock is released, unless a notification occurs.

Option C is incorrect because the thread will become a candidate immediately after notification, not two seconds afterwards.

Option D is also incorrect because a thread will not come out of a waiting pool just because a lock has been released.

Learn more problems on : Threads

Discuss about this problem : Discuss in Forum

19.

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

20.

What will be the output of the program?

class MyThread extends Thread 
{
    public static void main(String [] args) 
    {
        MyThread t = new MyThread();
        Thread x = new Thread(t);
        x.start(); /* Line 7 */
    }
    public void run() 
    {
        for(int i = 0; i < 3; ++i) 
        {
            System.out.print(i + "..");
        }
    }
}

A.
Compilation fails.
B.
1..2..3..
C.
0..1..2..3..
D.
0..1..2..

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

The thread MyThread will start and loop three times (from 0 to 2).

Option A is incorrect because the Thread class implements the Runnable interface; therefore, in line 7, Thread can take an object of type Thread as an argument in the constructor.

Option B and C are incorrect because the variable i in the for loop starts with a value of 0 and ends with a value of 2.

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.