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 cause a compiler error?

  1. float[ ] f = new float(3);
  2. float f2[ ] = new float[ ];
  3. float[ ]f1 = new float[3];
  4. float f3[ ] = new float[3];
  5. float f5[ ] = {1.0f, 2.0f, 2.0f};

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

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

(1) causes two compiler errors ( '[' expected and illegal start of expression) because the wrong type of bracket is used, ( ) instead of [ ]. The following is the correct syntax: float[ ] f = new float[3];

(2) causes a compiler error ( '{' expected ) because the array constructor does not specify the number of elements in the array. The following is the correct syntax: float f2[ ] = new float[3];

(3), (4), and (5) compile without error.

Learn more problems on : Declarations and Access Control

Discuss about this problem : Discuss in Forum

2.

public class Test { }
What is the prototype of the default constructor?

A.
Test( )
B.
Test(void)
C.
public Test( )
D.
public Test(void)

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

Option A and B are wrong because they use the default access modifier and the access modifier for the class is public (remember, the default constructor has the same access modifier as the class).

Option D is wrong. The void makes the compiler think that this is a method specification - in fact if it were a method specification the compiler would spit it out.

Learn more problems on : Declarations and Access Control

Discuss about this problem : Discuss in Forum

3.

What is the value of "d" after this line of code has been executed?

double d = Math.round ( 2.5 + Math.random() );

A.
2
B.
3
C.
4
D.
2.5

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

The Math.random() method returns a number greater than or equal to 0 and less than 1 . Since we can then be sure that the sum of that number and 2.5 will be greater than or equal to 2.5 and less than 3.5, we can be sure that Math.round() will round that number to 3. So Option B is the answer.

Learn more problems on : Java.lang Class

Discuss about this problem : Discuss in Forum

4.

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

A.
same results 0 time(s)
B.
same results 2 time(s)
C.
same results 4 time(s)
D.
Compilation fails.

Your Answer: Option (Not Answered)

Correct Answer: Option B

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.

Learn more problems on : Java.lang Class

Discuss about this problem : Discuss in Forum

5.

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

6.

Which constructs an anonymous inner class instance?

A.
Runnable r = new Runnable() { };
B.
Runnable r = new Runnable(public void run() { });
C.
Runnable r = new Runnable { public void run(){}};
D.
System.out.println(new Runnable() {public void run() { }});

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

D is correct. It defines an anonymous inner class instance, which also means it creates an instance of that new anonymous class at the same time. The anonymous class is an implementer of the Runnable interface, so it must override the run() method of Runnable.

A is incorrect because it doesn't override the run() method, so it violates the rules of interface implementation.

B and C use incorrect syntax.

Learn more problems on : Inner Classes

Discuss about this problem : Discuss in Forum

7.

What two statements are true about properly overridden hashCode() and equals() methods?

  1. hashCode() doesn't have to be overridden if equals() is.
  2. equals() doesn't have to be overridden if hashCode() is.
  3. hashCode() can always return the same value, regardless of the object that invoked it.
  4. equals() can be true even if it's comparing different objects.

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

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

(3) and (4) are correct.

(1) and (2) are incorrect because by contract hashCode() and equals() can't be overridden unless both are overridden.

Learn more problems on : Objects and Collections

Discuss about this problem : Discuss in Forum

8.

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

9.

What will be the output of the program?

public class Test 
{  
    public static void main(String args[]) 
    { 
        int i = 1, j = 0; 
        switch(i) 
        { 
            case 2: j += 6; 
            case 4: j += 1; 
            default: j += 2; 
            case 0: j += 4; 
        } 
        System.out.println("j = " + j); 
    } 
}

A.
j = 0
B.
j = 2
C.
j = 4
D.
j = 6

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

Because there are no break statements, the program gets to the default case and adds 2 to j, then goes to case 0 and adds 4 to the new j. The result is j = 6.

Learn more problems on : Flow Control

Discuss about this problem : Discuss in Forum

10.

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

11.

void start() {  
    A a = new A(); 
    B b = new B(); 
    a.s(b);  
    b = null; /* Line 5 */
    a = null;  /* Line 6 */
    System.out.println("start completed"); /* Line 7 */
} 
When is the B object, created in line 3, eligible for garbage collection?

A.
after line 5
B.
after line 6
C.
after line 7
D.
There is no way to be absolutely certain.

Your Answer: Option (Not Answered)

Correct Answer: Option D

Learn more problems on : Garbage Collections

Discuss about this problem : Discuss in Forum

12.

Which of the following are legal lines of code?

  1. int w = (int)888.8;
  2. byte x = (byte)1000L;
  3. long y = (byte)100;
  4. byte z = (byte)100L;

A.
1 and 2
B.
2 and 3
C.
3 and 4
D.
All statements are correct.

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

Statements (1), (2), (3), and (4) are correct. (1) is correct because when a floating-point number (a double in this case) is cast to an int, it simply loses the digits after the decimal.

(2) and (4) are correct because a long can be cast into a byte. If the long is over 127, it loses its most significant (leftmost) bits.

(3) actually works, even though a cast is not necessary, because a long can store a byte.

Learn more problems on : Operators and Assignments

Discuss about this problem : Discuss in Forum

13.

    
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

14.

What will be the output of the program?

import java.util.*;
public class NewTreeSet2 extends NewTreeSet 
{
    public static void main(String [] args) 
    {
        NewTreeSet2 t = new NewTreeSet2();
        t.count();
    }
}
protected class NewTreeSet
{
    void count() 
    {
        for (int x = 0; x < 7; x++,x++ ) 
        {
            System.out.print(" " + x);
        }
    }
}

A.
0 2 4
B.
0 2 4 6
C.
Compilation fails at line 2
D.
Compilation fails at line 10

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

Nonnested classes cannot be marked protected (or final for that matter), so the compiler will fail at protected class NewTreeSet.

Learn more problems on : Declarations and Access Control

Discuss about this problem : Discuss in Forum

15.

What will be the output of the program?

class s implements Runnable 
{ 
    int x, y; 
    public void run() 
    { 
        for(int i = 0; i < 1000; i++) 
            synchronized(this) 
            { 
                x = 12; 
                y = 12; 
            } 
        System.out.print(x + " " + y + " "); 
    } 
    public static void main(String args[]) 
    { 
        s run = new s(); 
        Thread t1 = new Thread(run); 
        Thread t2 = new Thread(run); 
        t1.start(); 
        t2.start(); 
    } 
}

A.
DeadLock
B.
It print 12 12 12 12
C.
Compilation Error
D.
Cannot determine output.

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

The program will execute without any problems and print 12 12 12 12.

Learn more problems on : Threads

Discuss about this problem : Discuss in Forum

16.

What will be the output of the program?

public class SyncTest 
{
    public static void main (String [] args) 
    {
        Thread t = new Thread() 
        {
            Foo f = new Foo();
            public void run() 
            {
                f.increase(20);
            }
        };
    t.start();
    }
}
class Foo 
{
    private int data = 23;
    public void increase(int amt) 
    {
        int x = data;
        data = x + amt;
    }
}
and assuming that data must be protected from corruption, what—if anything—can you add to the preceding code to ensure the integrity of data?

A.
Synchronize the run method.
B.
Wrap a synchronize(this) around the call to f.increase().
C.
The existing code will cause a runtime exception.
D.
Synchronize the increase() method

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

Option D is correct because synchronizing the code that actually does the increase will protect the code from being accessed by more than one thread at a time.

Option A is incorrect because synchronizing the run() method would stop other threads from running the run() method (a bad idea) but still would not prevent other threads with other runnables from accessing the increase() method.

Option B is incorrect for virtually the same reason as A—synchronizing the code that calls the increase() method does not prevent other code from calling the increase() method.

Learn more problems on : Threads

Discuss about this problem : Discuss in Forum

17.

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

A.
Compile time Error There is no start() method
B.
Will print in this order AB CD AB...
C.
Will print but not be able to predict the Order
D.
Will print in this order ABCD...ABCD...

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

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

Learn more problems on : Threads

Discuss about this problem : Discuss in Forum

18.

What will be the output of the program?

class MyThread extends Thread 
{
    MyThread() 
    {
        System.out.print(" MyThread");
    }
    public void run() 
    {
        System.out.print(" bar");
    }
    public void run(String s) 
    {
        System.out.println(" baz");
    }
}
public class TestThreads 
{
    public static void main (String [] args) 
    {
        Thread t = new MyThread() 
        {
            public void run() 
            {
                System.out.println(" foo");
            }
        };
        t.start();
    }
}

A.
foo
B.
MyThread foo
C.
MyThread bar
D.
foo bar

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

Option B is correct because in the first line of main we're constructing an instance of an anonymous inner class extending from MyThread. So the MyThread constructor runs and prints "MyThread". The next statement in main invokes start() on the new thread instance, which causes the overridden run() method (the run() method defined in the anonymous inner class) to be invoked, which prints "foo"

Learn more problems on : Threads

Discuss about this problem : Discuss in Forum

19.

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

20.

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

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