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 two are valid constructors for Thread?

  1. Thread(Runnable r, String name)
  2. Thread()
  3. Thread(int priority)
  4. Thread(Runnable r, ThreadGroup g)
  5. Thread(Runnable r, int priority)

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

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

(1) and (2) are both valid constructors for Thread.

(3), (4), and (5) are not legal Thread constructors, although (4) is close. If you reverse the arguments in (4), you'd have a valid constructor.

Learn more problems on : Threads

Discuss about this problem : Discuss in Forum


2.

public class Test2 
{
    public static int x;
    public static int foo(int y) 
    {
        return y * 2;
    }
    public static void main(String [] args) 
    {
        int z = 5;
        assert z > 0; /* Line 11 */
        assert z > 2: foo(z); /* Line 12 */
        if ( z < 7 )
            assert z > 4; /* Line 14 */

        switch (z) 
        {
            case 4: System.out.println("4 ");
            case 5: System.out.println("5 ");
            default: assert z < 10;
        }

        if ( z < 10 )
            assert z > 4: z++; /* Line 22 */
        System.out.println(z);
    }
}
which line is an example of an inappropriate use of assertions?

A.
Line 11
B.
Line 12
C.
Line 14
D.
Line 22

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

Assert statements should not cause side effects. Line 22 changes the value of z if the assert statement is false.

Option A is fine; a second expression in an assert statement is not required.

Option B is fine because it is perfectly acceptable to call a method with the second expression of an assert statement.

Option C is fine because it is proper to call an assert statement conditionally.

Learn more problems on : Assertions

Discuss about this problem : Discuss in Forum


3.

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


4.

What will be the output of the program?

interface Count 
{
    short counter = 0;
    void countUp();
}
public class TestCount implements Count 
{
    public static void main(String [] args) 
    {
        TestCount t = new TestCount();
        t.countUp();
    }
    public void countUp() 
    {
        for (int x = 6; x>counter; x--, ++counter) /* Line 14 */
        {
            System.out.print(" " + counter);
        }
    }
}

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

Your Answer: Option (Not Answered)

Correct Answer: Option E

Explanation:

The code will not compile because the variable counter is an interface variable that is by default final static. The compiler will complain at line 14 when the code attempts to increment counter.

Learn more problems on : Declarations and Access Control

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.

What will be the output of the program?

String d = "bookkeeper";
d.substring(1,7);
d = "w" + d;
d.append("woo");  /* Line 4 */
System.out.println(d);

A.
wookkeewoo
B.
wbookkeeper
C.
wbookkeewoo
D.
Compilation fails.

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

In line 4 the code calls a StringBuffer method, append() on a String object.

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?

System.out.println(Math.sqrt(-4D));

A.
-2
B.
NaN
C.
Compile Error
D.
Runtime Exception

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

It is not possible in regular mathematics to get a value for the square-root of a negative number therefore a NaN will be returned because the code is valid.

Learn more problems on : Java.lang Class

Discuss about this problem : Discuss in Forum


9.

What will be the output of the program?

String s = "ABC"; 
s.toLowerCase(); 
s += "def"; 
System.out.println(s);

A.
ABC
B.
abc
C.
ABCdef
D.
Compile Error

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

String objects are immutable. The object s above is set to "ABC". Now ask yourself if this object is changed and if so where - remember strings are immutable.

Line 2 returns a string object but does not change the originag string object s, so after line 2 s is still "ABC".

So what's happening on line 3? Java will treat line 3 like the following:

s = new StringBuffer().append(s).append("def").toString();

This effectively creates a new String object and stores its reference in the variable s, the old String object containing "ABC" is no longer referenced by a live thread and becomes available for garbage collection.

Learn more problems on : Java.lang Class

Discuss about this problem : Discuss in Forum


10.

Which collection class allows you to access its elements by associating a key with an element's value, and provides synchronization?

A.
java.util.SortedMap
B.
java.util.TreeMap
C.
java.util.TreeSet
D.
java.util.Hashtable

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

Hashtable is the only class listed that provides synchronized methods. If you need synchronization great; otherwise, use HashMap, it's faster.

Learn more problems on : Objects and Collections

Discuss about this problem : Discuss in Forum


11.

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


12.

What will be the output of the program?

int I = 0;
label:
    if (I < 2) {
    System.out.print("I is " + I);
    I++;
    continue label;
}

A.
I is 0
B.
I is 0 I is 1
C.
Compilation fails.
D.
None of the above

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

The code will not compile because a continue statement can only occur in a looping construct. If this syntax were legal, the combination of the continue and the if statements would create a kludgey kind of loop, but the compiler will force you to write cleaner code than this.

Learn more problems on : Flow Control

Discuss about this problem : Discuss in Forum


13.

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'); 
        } 
    } 
}

A.
ABDCBDCB
B.
ABCDABCD
C.
Compilation fails.
D.
An exception is thrown at runtime.

Your Answer: Option (Not Answered)

Correct Answer: Option A

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

Learn more problems on : Flow Control

Discuss about this problem : Discuss in Forum


14.

What will be the output of the program?

public class If2 
{
    static boolean b1, b2;
    public static void main(String [] args) 
    {
        int x = 0;
        if ( !b1 ) /* Line 7 */
        {
            if ( !b2 ) /* Line 9 */
            {
                b1 = true;
                x++;
                if ( 5 > 6 ) 
                {
                    x++;
                }
                if ( !b1 ) 
                    x = x + 10;
                else if ( b2 = true ) /* Line 19 */
                    x = x + 100;
                else if ( b1 | b2 ) /* Line 21 */
                    x = x + 1000;
            }
        }
        System.out.println(x);
    }
}

A.
0
B.
1
C.
101
D.
111

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

As instance variables, b1 and b2 are initialized to false. The if tests on lines 7 and 9 are successful so b1 is set to true and x is incremented. The next if test to succeed is on line 19 (note that the code is not testing to see if b2 is true, it is setting b2 to be true). Since line 19 was successful, subsequent else-if's (line 21) will be skipped.

Learn more problems on : Flow Control

Discuss about this problem : Discuss in Forum


15.

What will be the output of the program?

class Bitwise 
{
    public static void main(String [] args) 
    {
        int x = 11 & 9;
        int y = x ^ 3;
        System.out.println( y | 12 );
    }
}

A.
0
B.
7
C.
8
D.
14

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

The & operator produces a 1 bit when both bits are 1. The result of the & operation is 9. The ^ operator produces a 1 bit when exactly one bit is 1; the result of this operation is 10. The | operator produces a 1 bit when at least one bit is 1; the result of this operation is 14.

Learn more problems on : Operators and Assignments

Discuss about this problem : Discuss in Forum


16.

What will be the output of the program?

class Equals 
{
    public static void main(String [] args) 
    {
        int x = 100;
        double y = 100.1;
        boolean b = (x = y); /* Line 7 */
        System.out.println(b);
    }
}

A.
true
B.
false
C.
Compilation fails
D.
An exception is thrown at runtime

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

The code will not compile because in line 7, the line will work only if we use (x==y) in the line. The == operator compares values to produce a boolean, whereas the = operator assigns a value to variables.

Option A, B, and D are incorrect because the code does not get as far as compiling. If we corrected this code, the output would be false.

Learn more problems on : Operators and Assignments

Discuss about this problem : Discuss in Forum


17.

What will be the output of the program?

class BoolArray 
{
    boolean [] b = new boolean[3];
    int count = 0;

    void set(boolean [] x, int i) 
    {
        x[i] = true;
        ++count;
    }

    public static void main(String [] args) 
    {
        BoolArray ba = new BoolArray();
        ba.set(ba.b, 0);
        ba.set(ba.b, 2);
        ba.test();
    }

    void test() 
    {
        if ( b[0] && b[1] | b[2] )
            count++;
        if ( b[1] && b[(++count - 2)] )
            count += 7;
        System.out.println("count = " + count);
    }
}

A.
count = 0
B.
count = 2
C.
count = 3
D.
count = 4

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

The reference variables b and x both refer to the same boolean array. count is incremented for each call to the set() method, and once again when the first if test is true. Because of the && short circuit operator, count is not incremented during the second if test.

Learn more problems on : Operators and Assignments

Discuss about this problem : Discuss in Forum


18.

What is the numerical range of a char?

A.
-128 to 127
B.
-(215) to (215) - 1
C.
0 to 32767
D.
0 to 65535

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

A char is really a 16-bit integer behind the scenes, so it supports 216 (from 0 to 65535) values.

Learn more problems on : Language Fundamentals

Discuss about this problem : Discuss in Forum


19.

Which statement is true?

A.
All objects that are eligible for garbage collection will be garbage collected by the garbage collector.
B.
Objects with at least one reference will never be garbage collected.
C.
Objects from a class with the finalize() method overridden will never be garbage collected.
D.
Objects instantiated within anonymous inner classes are placed in the garbage collectible heap.

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

All objects are placed in the garbage collectible heap.

Option A is incorrect because the garbage collector makes no guarantees.

Option B is incorrect because islands of isolated objects can exist.

Option C is incorrect because finalize() has no such mystical powers.

Learn more problems on : Garbage Collections

Discuss about this problem : Discuss in Forum


20.

Which statement is true?

A.
Memory is reclaimed by calling Runtime.gc().
B.
Objects are not collected if they are accessible from live threads.
C.
An OutOfMemory error is only thrown if a single block of memory cannot be found that is large enough for a particular requirement.
D.
Objects that have finalize() methods always have their finalize() methods called before the program ends.

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

Option B is correct. If an object can be accessed from a live thread, it can't be garbage collected.

Option A is wrong. Runtime.gc() asks the garbage collector to run, but the garbage collector never makes any guarantees about when it will run or what unreachable objects it will free from memory.

Option C is wrong. The garbage collector runs immediately the system is out of memory before an OutOfMemoryException is thrown by the JVM.

Option D is wrong. If this were the case then the garbage collector would actively hang onto objects until a program finishes - this goes against the purpose of the garbage collector.

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.