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.

What will be the output of the program?

public class CommandArgsThree 
{
    public static void main(String [] args) 
    {
        String [][] argCopy = new String[2][2];
        int x;
        argCopy[0] = args;
        x = argCopy[0].length;
        for (int y = 0; y < x; y++) 
        {
            System.out.print(" " + argCopy[0][y]);
        }
    }
}

and the command-line invocation is

> java CommandArgsThree 1 2 3

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

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

In argCopy[0] = args;, the reference variable argCopy[0], which was referring to an array with two elements, is reassigned to an array (args) with three elements.

Learn more problems on : Language Fundamentals

Discuss about this problem : Discuss in Forum


2.

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


3.

Which one is a valid declaration of a boolean?

A.
boolean b1 = 0;
B.
boolean b2 = 'false';
C.
boolean b3 = false;
D.
boolean b4 = Boolean.false();
E.
boolean b5 = no;

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

A boolean can only be assigned the literal true or false.

Learn more problems on : Language Fundamentals

Discuss about this problem : Discuss in Forum


4.

Which of the following will produce an answer that is closest in value to a double, d, while not being greater than d?

A.
(int)Math.min(d);
B.
(int)Math.max(d);
C.
(int)Math.abs(d);
D.
(int)Math.floor(d);

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

The casting to an int is a smokescreen. Use a process of elimination to answer this question:

Option D is the correct answer, it is syntathecially correct and will consistently return a value less than d.

Option A and B are wrong because both the min() and max() methods require 2 arguments whereas here they are passed only one parameter.

Option C is wrong because it could return a value greater than d (if d was negative).

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 Q126 implements Runnable 
{ 
    private int x; 
    private int y; 

    public static void main(String [] args) 
    { 
        Q126 that = new Q126(); 
        (new Thread(that)).start( ); /* Line 8 */
        (new Thread(that)).start( ); /* Line 9 */
    } 
    public synchronized void run( ) /* Line 11 */
    { 
        for (;;) /* Line 13 */
        { 
            x++; 
            y++; 
            System.out.println("x = " + x + "y = " + y); 
        } 
    } 
}

A.
An error at line 11 causes compilation to fail
B.
Errors at lines 8 and 9 cause compilation to fail.
C.
The program prints pairs of values for x and y that might not always be the same on the same line (for example, "x=2, y=1")
D.
The program prints pairs of values for x and y that are always the same on the same line (for example, "x=1, y=1". In addition, each value appears once (for example, "x=1, y=1" followed by "x=2, y=2")

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

The synchronized code is the key to answering this question. Because x and y are both incremented inside the synchronized method they are always incremented together. Also keep in mind that the two threads share the same reference to the Q126 object.

Also note that because of the infinite loop at line 13, only one thread ever gets to execute.

Learn more problems on : Threads

Discuss about this problem : Discuss in Forum


6.

What will be the output of the program?

public class Test 
{
    public int aMethod()
    {
        static int i = 0;
        i++;
        return i;
    }
    public static void main(String args[])
    {
        Test test = new Test();
        test.aMethod();
        int j = test.aMethod();
        System.out.println(j);
    }
}

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

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

Compilation failed because static was an illegal start of expression - method variables do not have a modifier (they are always considered local).

Learn more problems on : Declarations and Access Control

Discuss about this problem : Discuss in Forum


7.

What will be the output of the program?

public class Test 
{  
    public static void main(String args[])
    { 
        class Foo 
        {
            public int i = 3;
        } 
        Object o = (Object)new Foo();
        Foo foo = (Foo)o;
        System.out.println("i = " + foo.i);
    }
}

A.
i = 3
B.
Compilation fails.
C.
i = 5
D.
A ClassCastException will occur.

Your Answer: Option (Not Answered)

Correct Answer: Option A

Learn more problems on : Declarations and Access Control

Discuss about this problem : Discuss in Forum


8.

What will be the output of the program?

public class Test 
{ 
    public static void leftshift(int i, int j) 
    {
        i <<= j; 
    } 
    public static void main(String args[]) 
    {
        int i = 4, j = 2; 
        leftshift(i, j); 
        System.out.printIn(i); 
    } 
}

A.
2
B.
4
C.
8
D.
16

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

Java only ever passes arguments to a method by value (i.e. a copy of the variable) and never by reference. Therefore the value of the variable i remains unchanged in the main method.

If you are clever you will spot that 16 is 4 multiplied by 2 twice, (4 * 2 * 2) = 16. If you had 16 left shifted by three bits then 16 * 2 * 2 * 2 = 128. If you had 128 right shifted by 2 bits then 128 / 2 / 2 = 32. Keeping these points in mind, you don't have to go converting to binary to do the left and right bit shifts.

Learn more problems on : Operators and Assignments

Discuss about this problem : Discuss in Forum


9.

What will be the output of the program (when you run with the -ea option) ?

public class Test 
{  
    public static void main(String[] args) 
    {
        int x = 0;  
        assert (x > 0) : "assertion failed"; /* Line 6 */
        System.out.println("finished"); 
    } 
}

A.
finished
B.
Compilation fails.
C.
An AssertionError is thrown.
D.
An AssertionError is thrown and finished is output.

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

An assertion Error is thrown as normal giving the output "assertion failed". The word "finished" is not printed (ensure you run with the -ea option)

Assertion failures are generally labeled in the stack trace with the file and line number from which they were thrown, and also in this case with the error's detail message "assertion failed". The detail message is supplied by the assert statement in line 6.

Learn more problems on : Assertions

Discuss about this problem : Discuss in Forum


10.

What will be the output of the program?

class Q207 
{ 
    public static void main(String[] args) 
    {
        int i1 = 5; 
        int i2 = 6; 
        String s1 = "7"; 
        System.out.println(i1 + i2 + s1); /* Line 8 */
    } 
}

A.
18
B.
117
C.
567
D.
Compiler error

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

This question is about the + (plus) operator and the overriden + (string cocatanation) operator. The rules that apply when you have a mixed expression of numbers and strings are:

If either operand is a String, the + operator concatenates the operands.

If both operands are numeric, the + operator adds the operands.

The expression on line 6 above can be read as "Add the values i1 and i2 together, then take the sum and convert it to a string and concatenate it with the String from the variable s1". In code, the compiler probably interprets the expression on line 8 above as:

System.out.println( new StringBuffer() 
    .append(new Integer(i1 + i2).toString()) 
    .append(s1) 
    .toString() ); 

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 = "ABCD"; 
String b = a.toLowerCase(); 
b.replace('a','d'); 
b.replace('b','c'); 
System.out.println(b);

A.
abcd
B.
ABCD
C.
dccd
D.
dcba

Your Answer: Option (Not Answered)

Correct Answer: Option A

Explanation:

String objects are immutable, they cannot be changed, in this case we are talking about the replace method which returns a new String object resulting from replacing all occurrences of oldChar in this string with newChar.

b.replace(char oldChar, char newChar);

But since this is only a temporary String it must either be put to use straight away i.e.

System.out.println(b.replace('a','d'));

Or a new variable must be assigned its value i.e.

String c = b.replace('a','d');

Learn more problems on : Java.lang Class

Discuss about this problem : Discuss in Forum


12.

You want subclasses in any package to have access to members of a superclass. Which is the most restrictive access that accomplishes this objective?

A.
public
B.
private
C.
protected
D.
transient

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

Access modifiers dictate which classes, not which instances, may access features.

Methods and variables are collectively known as members. Method and variable members are given access control in exactly the same way.

private makes a member accessible only from within its own class

protected makes a member accessible only to classes in the same package or subclass of the class

default access is very similar to protected (make sure you spot the difference) default access makes a member accessible only to classes in the same package.

public means that all other classes regardless of the package that they belong to, can access the member (assuming the class itself is visible)

final makes it impossible to extend a class, when applied to a method it prevents a method from being overridden in a subclass, when applied to a variable it makes it impossible to reinitialise a variable once it has been initialised

abstract declares a method that has not been implemented.

transient indicates that a variable is not part of the persistent state of an object.

volatile indicates that a thread must reconcile its working copy of the field with the master copy every time it accesses the variable.

After examining the above it should be obvious that the access modifier that provides the most restrictions for methods to be accessed from the subclasses of the class from another package is C - protected. A is also a contender but C is more restrictive, B would be the answer if the constraint was the "same package" instead of "any package" in other words the subclasses clause in the question eliminates default.

Learn more problems on : Declarations and Access Control

Discuss about this problem : Discuss in Forum


13.

What will be the output of the program?

package foo; 
import java.util.Vector; /* Line 2 */
private class MyVector extends Vector 
{
    int i = 1; /* Line 5 */
    public MyVector() 
    { 
        i = 2; 
    } 
} 
public class MyNewVector extends MyVector 
{
    public MyNewVector () 
    { 
        i = 4; /* Line 15 */
    } 
    public static void main (String args []) 
    { 
        MyVector v = new MyNewVector(); /* Line 19 */
    } 
}

A.
Compilation will succeed.
B.
Compilation will fail at line 3.
C.
Compilation will fail at line 5.
D.
Compilation will fail at line 15.

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

Option B is correct. The compiler complains with the error "modifier private not allowed here". The class is created private and is being used by another class on line 19.

Learn more problems on : Objects and Collections

Discuss about this problem : Discuss in Forum


14.

What will be the output of the program?

public class Test 
{ 
    private static float[] f = new float[2]; 
    public static void main (String[] args) 
    {
        System.out.println("f[0] = " + f[0]); 
    } 
}

A.
f[0] = 0
B.
f[0] = 0.0
C.
Compile Error
D.
Runtime Exception

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

The choices are between Option A and B, what this question is really testing is your knowledge of default values of an initialized array. This is an array type float i.e. it is a type that uses decimal point numbers therefore its initial value will be 0.0 and not 0

Learn more problems on : Objects and Collections

Discuss about this problem : Discuss in Forum


15.

class Foo 
{
    class Bar{ }
}
class Test 
{
    public static void main (String [] args) 
    {
        Foo f = new Foo();
        /* Line 10: Missing statement ? */
    }
}
which statement, inserted at line 10, creates an instance of Bar?

A.
Foo.Bar b = new Foo.Bar();
B.
Foo.Bar b = f.new Bar();
C.
Bar b = new f.Bar();
D.
Bar b = f.new Bar();

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

Option B is correct because the syntax is correct-using both names (the enclosing class and the inner class) in the reference declaration, then using a reference to the enclosing class to invoke new on the inner class.

Option A, C and D all use incorrect syntax. A is incorrect because it doesn't use a reference to the enclosing class, and also because it includes both names in the new.

C is incorrect because it doesn't use the enclosing class name in the reference variable declaration, and because the new syntax is wrong.

D is incorrect because it doesn't use the enclosing class name in the reference variable declaration.

Learn more problems on : Inner Classes

Discuss about this problem : Discuss in Forum


16.

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


17.

    
import java.awt.*;
class Ticker extends Component 
{
    public static void main (String [] args) 
    {
        Ticker t = new Ticker();
        /* Missing Statements ? */
    }
}
which two of the following statements, inserted independently, could legally be inserted into missing section of this code?
  1. boolean test = (Component instanceof t);
  2. boolean test = (t instanceof Ticker);
  3. boolean test = t.instanceof(Ticker);
  4. boolean test = (t instanceof Component);

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

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

(2) is correct because class type Ticker is part of the class hierarchy of t; therefore it is a legal use of the instanceof operator. (4) is also correct because Component is part of the hierarchy of t, because Ticker extends Component.

(1) is incorrect because the syntax is wrong. A variable (or null) always appears before the instanceof operator, and a type appears after it. (3) is incorrect because the statement is used as a method (t.instanceof(Ticker);), which is illegal.

Learn more problems on : Operators and Assignments

Discuss about this problem : Discuss in Forum


18.

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


19.

What will be the output of the program?

int i = l, j = -1; 
switch (i) 
{
    case 0, 1: j = 1; /* Line 4 */
    case 2: j = 2; 
    default: j = 0; 
} 
System.out.println("j = " + j); 

A.
j = -1
B.
j = 0
C.
j = 1
D.
Compilation fails.

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

The case statement takes only a single argument. The case statement on line 4 is given two arguments so the compiler complains.

Learn more problems on : Flow Control

Discuss about this problem : Discuss in Forum


20.

Which statement is true for the class java.util.HashSet?

A.
The elements in the collection are ordered.
B.
The collection is guaranteed to be immutable.
C.
The elements in the collection are guaranteed to be unique.
D.
The elements in the collection are accessed using a unique key.

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

Option C is correct. HashSet implements the Set interface and the Set interface specifies collection that contains no duplicate elements.

Option A is wrong. HashSet makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time.

Option B is wrong. The set can be modified.

Option D is wrong. This is a Set and not a Map.

Learn more problems on : Objects and Collections

Discuss about this problem : Discuss in Forum


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