Online Java Programming Test - Java Programming Test - Random

Instruction:

  • This is a FREE online test. Beware of scammers who ask for money to attend this test.
  • Total number of questions: 20.
  • Time allotted: 30 minutes.
  • Each question carries 1 mark; there are no negative marks.
  • DO NOT refresh the page.
  • All the best!

Marks : 2/20


Total number of questions
20
Number of answered questions
0
Number of unanswered questions
20
Test Review : View answers and explanation for this test.

1.
Which one is a valid declaration of a boolean?
boolean b1 = 0;
boolean b2 = 'false';
boolean b3 = false;
boolean b4 = Boolean.false();
boolean b5 = no;
Your Answer: Option
(Not Answered)
Correct Answer: Option
Explanation:
A boolean can only be assigned the literal true or false.

2.
public class F0091 
{    
    public void main( String[] args ) 
    {  
        System.out.println( "Hello" + args[0] ); 
    } 
}

What will be the output of the program, if this code is executed with the command line:

> java F0091 world

Hello
Hello Foo91
Hello world
The code does not run.
Your Answer: Option
(Not Answered)
Correct Answer: Option
Explanation:

Option D is correct. A runtime error will occur owning to the main method of the code fragment not being declared static:

Exception in thread "main" java.lang.NoSuchMethodError: main

The Java Language Specification clearly states: "The main method must be declared public, static, and void. It must accept a single argument that is an array of strings."


3.
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 + ", ");
    }
}
10, 9, 8, 7, 6,
9, 8, 7, 6, 5,
Compilation fails.
An exception is thrown at runtime.
Your Answer: Option
(Not Answered)
Correct Answer: Option
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.


4.
Which is a valid declaration within an interface?
public static short stop = 23;
protected short stop = 23;
transient short stop = 23;
final void madness(short stop);
Your Answer: Option
(Not Answered)
Correct Answer: Option
Explanation:

(A) is valid interface declarations.

(B) and (C) are incorrect because interface variables cannot be either protected or transient. (D) is incorrect because interface methods cannot be final or static.


5.
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.
1, 2 and 4
2, 3 and 5
3, 4 and 5
1, 2 and 3
Your Answer: Option
(Not Answered)
Correct Answer: Option
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.


6.
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;
    }
}
true true
false true
true false
false false
Your Answer: Option
(Not Answered)
Correct Answer: Option
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.


7.
What will be the output of the program?
public class Delta 
{ 
    static boolean foo(char c) 
    {
        System.out.print(c); 
        return true; 
    } 
    public static void main( String[] argv ) 
    {
        int i = 0; 
        for (foo('A'); foo('B') && (i < 2); foo('C')) 
        {
            i++; 
            foo('D'); 
        } 
    } 
}
ABDCBDCB
ABCDABCD
Compilation fails.
An exception is thrown at runtime.
Your Answer: Option
(Not Answered)
Correct Answer: Option
Explanation:

'A' is only printed once at the very start as it is in the initialisation section of the for loop. The loop will only initialise that once.

'B' is printed as it is part of the test carried out in order to run the loop.

'D' is printed as it is in the loop.

'C' is printed as it is in the increment section of the loop and will 'increment' only at the end of each loop. Here ends the first loop. Again 'B' is printed as part of the loop test.

'D' is printed as it is in the loop.

'C' is printed as it 'increments' at the end of each loop.

Again 'B' is printed as part of the loop test. At this point the test fails because the other part of the test (i < 2) is no longer true. i has been increased in value by 1 for each loop with the line: i++;

This results in a printout of ABDCBDCB


8.
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);
1
2
3
4
Your Answer: Option
(Not Answered)
Correct Answer: Option
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.


9.
What will be the output of the program?
public class RTExcept 
{
    public static void throwit () 
    {
        System.out.print("throwit ");
        throw new RuntimeException();
    }
    public static void main(String [] args) 
    {
        try 
        {
            System.out.print("hello ");
            throwit();
        }
        catch (Exception re ) 
        {
            System.out.print("caught ");
        }
        finally 
        {
            System.out.print("finally ");
        }
        System.out.println("after ");
    }
}
hello throwit caught
Compilation fails
hello throwit RuntimeException caught after
hello throwit caught finally after
Your Answer: Option
(Not Answered)
Correct Answer: Option
Explanation:

The main() method properly catches and handles the RuntimeException in the catch block, finally runs (as it always does), and then the code returns to normal.

A, B and C are incorrect based on the program logic described above. Remember that properly handled exceptions do not cause the program to stop executing.


10.
Which statement is true?
A try statement must have at least one corresponding catch block.
Multiple catch statements can catch the same class of exception more than once.
An Error that might be thrown in a method must be declared as thrown by that method, or be handled within that method.
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
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.


11.
Which interface does java.util.Hashtable implement?
Java.util.Map
Java.util.List
Java.util.HashTable
Java.util.Collection
Your Answer: Option
(Not Answered)
Correct Answer: Option
Explanation:

Hash table based implementation of the Map interface.


12.
class Boo 
{
    Boo(String s) { }
    Boo() { }
}
class Bar extends Boo 
{
    Bar() { }
    Bar(String s) {super(s);}
    void zoo() 
    {
    // insert code here
    }
}
which one create an anonymous inner class from within class Bar?
Boo f = new Boo(24) { };
Boo f = new Bar() { };
Bar f = new Boo(String s) { };
Boo f = new Boo.Bar(String s) { };
Your Answer: Option
(Not Answered)
Correct Answer: Option
Explanation:

Option B is correct because anonymous inner classes are no different from any other class when it comes to polymorphism. That means you are always allowed to declare a reference variable of the superclass type and have that reference variable refer to an instance of a subclass type, which in this case is an anonymous subclass of Bar. Since Bar is a subclass of Boo, it all works.

Option A is incorrect because it passes an int to the Boo constructor, and there is no matching constructor in the Boo class.

Option C is incorrect because it violates the rules of polymorphism—you cannot refer to a superclass type using a reference variable declared as the subclass type. The superclass is not guaranteed to have everything the subclass has.

Option D uses incorrect syntax.


13.
Which three are methods of the Object class?
  1. notify();
  2. notifyAll();
  3. isInterrupted();
  4. synchronized();
  5. interrupt();
  6. wait(long msecs);
  7. sleep(long msecs);
  8. yield();
1, 2, 4
2, 4, 5
1, 2, 6
2, 3, 4
Your Answer: Option
(Not Answered)
Correct Answer: Option
Explanation:

(1), (2), and (6) are correct. They are all related to the list of threads waiting on the specified object.

(3), (5), (7), and (8) are incorrect answers. The methods isInterrupted() and interrupt() are instance methods of Thread.

The methods sleep() and yield() are static methods of Thread.

D is incorrect because synchronized is a keyword and the synchronized() construct is part of the Java language.


14.
Which class or interface defines the wait(), notify(),and notifyAll() methods?
Object
Thread
Runnable
Class
Your Answer: Option
(Not Answered)
Correct Answer: Option
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.


15.
What will be the output of the program?
class s1 extends Thread
{ 
    public void run() 
    { 
        for(int i = 0; i < 3; i++) 
        { 
            System.out.println("A"); 
            System.out.println("B"); 
        } 
    } 
} 
class Test120 extends Thread 
{ 
    public void run() 
    { 
        for(int i = 0; i < 3; i++) 
        { 
            System.out.println("C"); 
            System.out.println("D"); 
        } 
    } 
    public static void main(String args[]) 
        { 
        s1 t1 = new s1(); 
        Test120 t2 = new Test120(); 
        t1.start(); 
        t2.start(); 
    } 
}
Compile time Error There is no start() method
Will print in this order AB CD AB...
Will print but not be able to predict the Order
Will print in this order ABCD...ABCD...
Your Answer: Option
(Not Answered)
Correct Answer: Option
Explanation:

We cannot predict the order in which threads are going to run.


16.
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 + "..");
        }
    }
}
Compilation fails.
1..2..3..
0..1..2..3..
0..1..2..
Your Answer: Option
(Not Answered)
Correct Answer: Option
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.


17.
What will be the output of the program?
public class Example 
{
    public static void main(String [] args) 
    {
        double values[] = {-2.3, -1.0, 0.25, 4};
        int cnt = 0;
        for (int x=0; x < values.length; x++) 
        {
            if (Math.round(values[x] + .5) == Math.ceil(values[x])) 
            {
                ++cnt;
            }
        }
        System.out.println("same results " + cnt + " time(s)");
    }
}
same results 0 time(s)
same results 2 time(s)
same results 4 time(s)
Compilation fails.
Your Answer: Option
(Not Answered)
Correct Answer: Option
Explanation:

Math.round() adds .5 to the argument then performs a floor(). Since the code adds an additional .5 before round() is called, it's as if we are adding 1 then doing a floor(). The values that start out as integer values will in effect be incremented by 1 on the round() side but not on the ceil() side, and the noninteger values will end up equal.


18.
What will be the output of the program?
public class Test178 
{ 
    public static void main(String[] args) 
    {
        String s = "foo"; 
        Object o = (Object)s; 
        if (s.equals(o)) 
        { 
            System.out.print("AAA"); 
        } 
        else 
        {
            System.out.print("BBB"); 
        } 
        if (o.equals(s)) 
        {
            System.out.print("CCC"); 
        } 
        else 
        {
            System.out.print("DDD"); 
        } 
    } 
}
AAACCC
AAADDD
BBBCCC
BBBDDD
Your Answer: Option
(Not Answered)
Correct Answer: Option

19.
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);
    }
}
result = 1
result = 10
result = 11
result = 11010
Your Answer: Option
(Not Answered)
Correct Answer: Option
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.


20.
What will be the output of the program?
public class StringRef 
{
    public static void main(String [] args) 
    {
        String s1 = "abc";
        String s2 = "def";
        String s3 = s2;   /* Line 7 */
        s2 = "ghi";
        System.out.println(s1 + s2 + s3);
    }
}
abcdefghi
abcdefdef
abcghidef
abcghighi
Your Answer: Option
(Not Answered)
Correct Answer: Option
Explanation:

After line 7 executes, both s2 and s3 refer to a String object that contains the value "def". When line 8 executes, a new String object is created with the value "ghi", to which s2 refers. The reference variable s3 still refers to the (immutable) String object with the value "def".


*** END OF THE TEST ***
Time Left: 00:29:56
Post your test result / feedback here: