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.

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


2.

Which three guarantee that a thread will leave the running state?

  1. yield()
  2. wait()
  3. notify()
  4. notifyAll()
  5. sleep(1000)
  6. aLiveThread.join()
  7. Thread.killThread()

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

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

(2) is correct because wait() always causes the current thread to go into the object's wait pool.

(5) is correct because sleep() will always pause the currently running thread for at least the duration specified in the sleep argument (unless an interrupted exception is thrown).

(6) is correct because, assuming that the thread you're calling join() on is alive, the thread calling join() will immediately block until the thread you're calling join() on is no longer alive.

(1) is wrong, but tempting. The yield() method is not guaranteed to cause a thread to leave the running state, although if there are runnable threads of the same priority as the currently running thread, then the current thread will probably leave the running state.

(3) and (4) are incorrect because they don't cause the thread invoking them to leave the running state.

(7) is wrong because there's no such method.

Learn more problems on : Threads

Discuss about this problem : Discuss in Forum


3.

Which is a valid declarations of a String?

A.
String s1 = null;
B.
String s2 = 'null';
C.
String s3 = (String) 'abc';
D.
String s4 = (String) '\ufeed';

Your Answer: Option (Not Answered)

Correct Answer: Option A

Explanation:

Option A sets the String reference to null.

Option B is wrong because null cannot be in single quotes.

Option C is wrong because there are multiple characters between the single quotes ('abc').

Option D is wrong because you can't cast a char (primitive) to a String (object).

Learn more problems on : Language Fundamentals

Discuss about this problem : Discuss in Forum


4.

What will be the output of the program?

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

    void start() 
    {
        long [] a1 = {3,4,5};
        long [] a2 = fix(a1);
        System.out.print(a1[0] + a1[1] + a1[2] + " ");
        System.out.println(a2[0] + a2[1] + a2[2]);
    }

    long [] fix(long [] a3) 
    {
        a3[1] = 7;
        return a3;
    }
}

A.
12 15
B.
15 15
C.
3 4 5 3 7 5
D.
3 7 5 3 7 5

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

Output: 15 15

The reference variables a1 and a3 refer to the same long array object. When the [1] element is updated in the fix() method, it is updating the array referred to by a1. The reference variable a2 refers to the same array object.

So Output: 3+7+5+" "3+7+5

Output: 15 15 Because Numeric values will be added

Learn more problems on : Operators and Assignments

Discuss about this problem : Discuss in Forum


5.

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


6.

What will be the output of the program?

class A 
{
    final public int GetResult(int a, int b) { return 0; } 
} 
class B extends A 
{ 
    public int GetResult(int a, int b) {return 1; } 
} 
public class Test 
{
    public static void main(String args[]) 
    { 
        B b = new B(); 
        System.out.println("x = " + b.GetResult(0, 1));  
    } 
}

A.
x = 0
B.
x = 1
C.
Compilation fails.
D.
An exception is thrown at runtime.

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

The code doesn't compile because the method GetResult() in class A is final and so cannot be overridden.

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.

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

A.
Hello
B.
Hello Foo91
C.
Hello world
D.
The code does not run.

Your Answer: Option (Not Answered)

Correct Answer: Option D

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."

Learn more problems on : Language Fundamentals

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) 
    {
        signed int x = 10;
        for (int y=0; y<5; y++, x--)
            System.out.print(x + ", ");
    }
}

A.
10, 9, 8, 7, 6,
B.
9, 8, 7, 6, 5,
C.
Compilation fails.
D.
An exception is thrown at runtime.

Your Answer: Option (Not Answered)

Correct Answer: Option C

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.

Learn more problems on : Language Fundamentals

Discuss about this problem : Discuss in Forum


10.

What will be the output of the program?

boolean bool = true; 
if(bool = false) /* Line 2 */
{
    System.out.println("a"); 
} 
else if(bool) /* Line 6 */
{
    System.out.println("b"); 
} 
else if(!bool) /* Line 10 */
{
    System.out.println("c"); /* Line 12 */
} 
else 
{
    System.out.println("d"); 
}

A.
a
B.
b
C.
c
D.
d

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

Look closely at line 2, is this an equality check (==) or an assignment (=). The condition at line 2 evaluates to false and also assigns false to bool. bool is now false so the condition at line 6 is not true. The condition at line 10 checks to see if bool is not true ( if !(bool == true) ), it isn't so line 12 is executed.

Learn more problems on : Flow Control

Discuss about this problem : Discuss in Forum


11.

What is the most restrictive access modifier that will allow members of one class to have access to members of another class in the same package?

A.
public
B.
abstract
C.
protected
D.
synchronized
E.
default access

Your Answer: Option (Not Answered)

Correct Answer: Option E

Explanation:

default access is the "package oriented" access modifier.

Option A and C are wrong because public and protected are less restrictive. Option B and D are wrong because abstract and synchronized are not access modifiers.

Learn more problems on : Declarations and Access Control

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.

import java.io.*;
public class MyProgram 
{
    public static void main(String args[])
    {
        FileOutputStream out = null;
        try 
        {
            out = new FileOutputStream("test.txt");
            out.write(122);
        }
        catch(IOException io) 
        {
            System.out.println("IO Error.");
        }
        finally 
        {
            out.close();
        }
    }
}
and given that all methods of class FileOutputStream, including close(), throw an IOException, which of these is true?

A.
This program will compile successfully.
B.
This program fails to compile due to an error at line 4.
C.
This program fails to compile due to an error at line 6.
D.
This program fails to compile due to an error at line 18.

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

Any method (in this case, the main() method) that throws a checked exception (in this case, out.close() ) must be called within a try clause, or the method must declare that it throws the exception. Either main() must declare that it throws an exception, or the call to out.close() in the finally block must fall inside a (in this case nested) try-catch block.

Learn more problems on : Exceptions

Discuss about this problem : Discuss in Forum


14.

Which of the following are Java reserved words?

  1. run
  2. import
  3. default
  4. implement

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

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

(2) - This is a Java keyword

(3) - This is a Java keyword

(1) - Is incorrect because although it is a method of Thread/Runnable it is not a keyword

(4) - This is not a Java keyword the keyword is implements

Learn more problems on : Objects and Collections

Discuss about this problem : Discuss in Forum


15.

class Test1 
{
    public int value;
    public int hashCode() { return 42; }
}
class Test2 
{
    public int value;
    public int hashcode() { return (int)(value^5); }
}
which statement is true?

A.
class Test1 will not compile.
B.
The Test1 hashCode() method is more efficient than the Test2 hashCode() method.
C.
The Test1 hashCode() method is less efficient than the Test2 hashCode() method.
D.
class Test2 will not compile.

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

The so-called "hashing algorithm" implemented by class Test1 will always return the same value, 42, which is legal but which will place all of the hash table entries into a single bucket, the most inefficient setup possible.

Option A and D are incorrect because these classes are legal.

Option B is incorrect based on the logic described above.

Learn more problems on : Objects and Collections

Discuss about this problem : Discuss in Forum


16.

What will be the output of the program?

TreeSet map = new TreeSet();
map.add("one");
map.add("two");
map.add("three");
map.add("four");
map.add("one");
Iterator it = map.iterator();
while (it.hasNext() ) 
{
    System.out.print( it.next() + " " );
}

A.
one two three four
B.
four three two one
C.
four one three two
D.
one two three four one

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

TreeSet assures no duplicate entries; also, when it is accessed it will return elements in natural order, which typically means alphabetical.

Learn more problems on : Objects and Collections

Discuss about this problem : Discuss in Forum


17.

What will be the output of the program?

public class HorseTest 
{
    public static void main (String [] args) 
    {
        class Horse 
        {
            public String name; /* Line 7 */
            public Horse(String s) 
            {
                name = s;
            }
        } /* class Horse ends */
        
        Object obj = new Horse("Zippo"); /* Line 13 */
        Horse h = (Horse) obj; /* Line 14 */
        System.out.println(h.name);
    }
} /* class HorseTest ends */

A.
An exception occurs at runtime at line 10.
B.
It prints "Zippo".
C.
Compilation fails because of an error on line 7.
D.
Compilation fails because of an error on line 13.

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

The code in the HorseTest class is perfectly legal. Line 13 creates an instance of the method-local inner class Horse, using a reference variable declared as type Object. Line 14 casts the Horse object to a Horse reference variable, which allows line 15 to compile. If line 14 were removed, the HorseTest code would not compile, because class Object does not have a name variable.

Learn more problems on : Inner Classes

Discuss about this problem : Discuss in Forum


18.

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


19.

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


20.

Which statement is true?

A.
If only one thread is blocked in the wait method of an object, and another thread executes the modify on that same object, then the first thread immediately resumes execution.
B.
If a thread is blocked in the wait method of an object, and another thread executes the notify method on the same object, it is still possible that the first thread might never resume execution.
C.
If a thread is blocked in the wait method of an object, and another thread executes the notify method on the same object, then the first thread definitely resumes execution as a direct and sole consequence of the notify call.
D.
If two threads are blocked in the wait method of one object, and another thread executes the notify method on the same object, then the first thread that executed the wait call first definitely resumes execution as a direct and sole consequence of the notify call.

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

Option B is correct - The notify method only wakes the thread. It does not guarantee that the thread will run.

Option A is incorrect - just because another thread activates the modify method in A this does not mean that the thread will automatically resume execution

Option C is incorrect - This is incorrect because as said in Answer B notify only wakes the thread but further to this once it is awake it goes back into the stack and awaits execution therefore it is not a "direct and sole consequence of the notify call"

Option D is incorrect - The notify method wakes one waiting thread up. If there are more than one sleeping threads then the choice as to which thread to wake is made by the machine rather than you therefore you cannot guarantee that the notify'ed thread will be the first waiting thread.

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.