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.

You need to store elements in a collection that guarantees that no duplicates are stored and all elements can be accessed in natural order. Which interface provides that capability?

A.
java.util.Map
B.
java.util.Set
C.
java.util.List
D.
java.util.Collection

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

Option B is correct. A set is a collection that contains no duplicate elements. The iterator returns the elements in no particular order (unless this set is an instance of some class that provides a guarantee). A map cannot contain duplicate keys but it may contain duplicate values. List and Collection allow duplicate elements.

Option A is wrong. A map is an object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value. The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order (ascending key order); others, like the HashMap class, do not (does not guarantee that the order will remain constant over time).

Option C is wrong. A list is an ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list. Unlike sets, lists typically allow duplicate elements.

Option D is wrong. A collection is also known as a sequence. The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list. Unlike sets, lists typically allow duplicate elements.

Learn more problems on : Objects and Collections

Discuss about this problem : Discuss in Forum


2.

What will be the output of the program?

class Super
{ 
    public int i = 0; 

    public Super(String text) /* Line 4 */
    {
        i = 1; 
    } 
} 

class Sub extends Super
{
    public Sub(String text)
    {
        i = 2; 
    } 

    public static void main(String args[])
    {
        Sub sub = new Sub("Hello"); 
        System.out.println(sub.i); 
    } 
}

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

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

A default no-args constructor is not created because there is a constructor supplied that has an argument, line 4. Therefore the sub-class constructor must explicitly make a call to the super class constructor:

public Sub(String text)
{ 
    super(text); // this must be the first line constructor 
    i = 2; 
}

Learn more problems on : Declarations and Access Control

Discuss about this problem : Discuss in Forum


3.

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


4.

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


5.

What will be the output of the program?

Float f = new Float("12"); 
switch (f) 
{
    case 12: System.out.println("Twelve"); 
    case 0: System.out.println("Zero"); 
    default: System.out.println("Default"); 
}

A.
Zero
B.
Twelve
C.
Default
D.
Compilation fails

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

The switch statement can only be supported by integers or variables more "narrow" than an integer i.e. byte, char, short. Here a Float wrapper object is used and so the compilation fails.

Learn more problems on : Flow Control

Discuss about this problem : Discuss in Forum


6.

What will be the output of the program?

int i = 0, j = 5; 
tp: for (;;) 
    {
        i++;  
        for (;;) 
        {
            if(i > --j) 
            {
                break tp; 
            } 
        } 
        System.out.println("i =" + i + ", j = " + j);

A.
i = 1, j = 0
B.
i = 1, j = 4
C.
i = 3, j = 4
D.
Compilation fails.

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

If you examine the code carefully you will notice a missing curly bracket at the end of the code, this would cause the code to fail.

Learn more problems on : Flow Control

Discuss about this problem : Discuss in Forum


7.

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


8.

What will be the output of the program?

class Two 
{
    byte x;
}

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

    void start() 
    {
        Two t = new Two();
        System.out.print(t.x + " ");
        Two t2 = fix(t);
        System.out.println(t.x + " " + t2.x);
    }

    Two fix(Two tt) 
    {
        tt.x = 42;
        return tt;
    }
}

A.
null null 42
B.
0 0 42
C.
0 42 42
D.
0 0 0

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

In the fix() method, the reference variable tt refers to the same object (class Two) as the t reference variable. Updating tt.x in the fix() method updates t.x (they are one in the same object). Remember also that the instance variable x in the Two class is initialized to 0.

Learn more problems on : Operators and Assignments

Discuss about this problem : Discuss in Forum


9.

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


10.

What will be the output of the program?

String s = "hello"; 
Object o = s; 
if( o.equals(s) )
{
    System.out.println("A"); 
} 
else
{
    System.out.println("B"); 
} 
if( s.equals(o) )
{
    System.out.println("C"); 
} 
else
{ 
    System.out.println("D"); 
}
  1. A
  2. B
  3. C
  4. D

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

Your Answer: Option (Not Answered)

Correct Answer: Option A

Learn more problems on : Java.lang Class

Discuss about this problem : Discuss in Forum


11.

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


12.

What will be the output of the program?

public abstract class AbstractTest 
{
    public int getNum() 
    {
        return 45;
    }
    public abstract class Bar 
    {
        public int getNum() 
        {
            return 38;
        }
    }
    public static void main (String [] args) 
    {
        AbstractTest t = new AbstractTest() 
        {
            public int getNum() 
            {
                return 22;
            }
        };
        AbstractTest.Bar f = t.new Bar() 
        {
            public int getNum() 
            {
                return 57;
            }
        };
        
        System.out.println(f.getNum() + " " + t.getNum());
    }
}

A.
57 22
B.
45 38
C.
45 57
D.
An exception occurs at runtime.

Your Answer: Option (Not Answered)

Correct Answer: Option A

Explanation:

You can define an inner class as abstract, which means you can instantiate only concrete subclasses of the abstract inner class. The object referenced by the variable t is an instance of an anonymous subclass of AbstractTest, and the anonymous class overrides the getNum() method to return 22. The variable referenced by f is an instance of an anonymous subclass of Bar, and the anonymous Bar subclass also overrides the getNum() method (to return 57). Remember that to instantiate a Bar instance, we need an instance of the enclosing AbstractTest class to tie to the new Bar inner class instance. AbstractTest can't be instantiated because it's abstract, so we created an anonymous subclass (non-abstract) and then used the instance of that anonymous subclass to tie to the new Bar subclass instance.

Learn more problems on : Inner Classes

Discuss about this problem : Discuss in Forum


13.

What will be the output of the program?

public class Foo 
{
    Foo() 
    {
        System.out.print("foo");
    }
    
class Bar
{
    Bar() 
    {
        System.out.print("bar");
    }
    public void go() 
    {
        System.out.print("hi");
    }
} /* class Bar ends */

    public static void main (String [] args) 
    {
        Foo f = new Foo();
        f.makeBar();
    }
    void makeBar() 
    {
        (new Bar() {}).go();
    }
}/* class Foo ends */

A.
Compilation fails.
B.
An error occurs at runtime.
C.
It prints "foobarhi"
D.
It prints "barhi"

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

Option C is correct because first the Foo instance is created, which means the Foo constructor runs and prints "foo". Next, the makeBar() method is invoked which creates a Bar, which means the Bar constructor runs and prints "bar", and finally the go() method is invoked on the new Bar instance, which means the go() method prints "hi".

Learn more problems on : Inner Classes

Discuss about this problem : Discuss in Forum


14.

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


15.

public interface Foo 
{ 
    int k = 4; /* Line 3 */
}
Which three piece of codes are equivalent to line 3?
  1. final int k = 4;
  2. public int k = 4;
  3. static int k = 4;
  4. abstract int k = 4;
  5. volatile int k = 4;
  6. protected int k = 4;

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

Your Answer: Option (Not Answered)

Correct Answer: Option A

Explanation:

(1), (2) and (3) are correct. Interfaces can have constants, which are always implicitly public, static, and final. Interface constant declarations of public, static, and final are optional in any combination.

Learn more problems on : Language Fundamentals

Discuss about this problem : Discuss in Forum


16.

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() 
    {
        throw new Error(); /* Line 22 */
    } 
}

A.
ABCD
B.
Compilation fails.
C.
C is printed before exiting with an error message.
D.
BC is printed before exiting with an error message.

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

Error is thrown but not recognised line(22) because the only catch attempts to catch an Exception and Exception is not a superclass of Error. Therefore only the code in the finally statement can be run before exiting with a runtime error (Exception in thread "main" java.lang.Error).

Learn more problems on : Exceptions

Discuss about this problem : Discuss in Forum


17.

What will be the output of the program?

class Exc0 extends Exception { } 
class Exc1 extends Exc0 { } /* Line 2 */
public class Test 
{  
    public static void main(String args[]) 
    { 
        try 
        {  
            throw new Exc1(); /* Line 9 */
        } 
        catch (Exc0 e0) /* Line 11 */
        {
            System.out.println("Ex0 caught"); 
        } 
        catch (Exception e) 
        {
            System.out.println("exception caught");  
        } 
    } 
}

A.
Ex0 caught
B.
exception caught
C.
Compilation fails because of an error at line 2.
D.
Compilation fails because of an error at line 9.

Your Answer: Option (Not Answered)

Correct Answer: Option A

Explanation:

An exception Exc1 is thrown and is caught by the catch statement on line 11. The code is executed in this block. There is no finally block of code to execute.

Learn more problems on : Exceptions

Discuss about this problem : Discuss in Forum


18.

What will be the output of the program?

public class WaitTest 
{
    public static void main(String [] args) 
    {
        System.out.print("1 ");
        synchronized(args)
        {
            System.out.print("2 ");
            try 
            {
                    args.wait(); /* Line 11 */
            }
            catch(InterruptedException e){ }
        }
        System.out.print("3 ");
    }
}

A.
It fails to compile because the IllegalMonitorStateException of wait() is not dealt with in line 11.
B.
1 2 3
C.
1 3
D.
1 2

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

1 and 2 will be printed, but there will be no return from the wait call because no other thread will notify the main thread, so 3 will never be printed. The program is essentially frozen at line 11.

A is incorrect; IllegalMonitorStateException is an unchecked exception so it doesn't have to be dealt with explicitly.

B and C are incorrect; 3 will never be printed, since this program will never terminate because it will wait forever.

Learn more problems on : Threads

Discuss about this problem : Discuss in Forum


19.

Which statement is true?

A.
Programs will not run out of memory.
B.
Objects that will never again be used are eligible for garbage collection.
C.
Objects that are referred to by other objects will never be garbage collected.
D.
Objects that can be reached from a live thread will never be garbage collected.

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

Option D is correct.

Option C is wrong. See the note above on Islands of Isolation (An object is eligible for garbage collection when no live thread can access it - even though there might be references to it).

Option B is wrong. "Never again be used" does not mean that there are no more references to the object.

Option A is wrong. Even though Java applications can run out of memory there another answer supplied that is more right.

Learn more problems on : Garbage Collections

Discuss about this problem : Discuss in Forum


20.

class HappyGarbage01 
{ 
    public static void main(String args[]) 
    {
        HappyGarbage01 h = new HappyGarbage01(); 
        h.methodA(); /* Line 6 */
    } 
    Object methodA() 
    {
        Object obj1 = new Object(); 
        Object [] obj2 = new Object[1]; 
        obj2[0] = obj1; 
        obj1 = null; 
        return obj2[0]; 
    } 
}
Where will be the most chance of the garbage collector being invoked?

A.
After line 9
B.
After line 10
C.
After line 11
D.
Garbage collector never invoked in methodA()

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

Option D is correct. Garbage collection takes place after the method has returned its reference to the object. The method returns to line 6, there is no reference to store the return value. so garbage collection takes place after line 6.

Option A is wrong. Because the reference to obj1 is stored in obj2[0]. The Object obj1 still exists on the heap and can be accessed by an active thread through the reference stored in obj2[0].

Option B is wrong. Because it is only one of the references to the object obj1, the other reference is maintained in obj2[0].

Option C is wrong. The garbage collector will not be called here because a reference to the object is being maintained and returned in obj2[0].

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.