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.

public class While 
{
    public void loop() 
    {
        int x= 0;
        while ( 1 ) /* Line 6 */
        {
            System.out.print("x plus one is " + (x + 1)); /* Line 8 */
        }
    }
}
Which statement is true?

A.
There is a syntax error on line 1.
B.
There are syntax errors on lines 1 and 6.
C.
There are syntax errors on lines 1, 6, and 8.
D.
There is a syntax error on line 6.

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

Using the integer 1 in the while statement, or any other looping or conditional construct for that matter, will result in a compiler error. This is old C Program syntax, not valid Java.

A, B and C are incorrect because line 1 is valid (Java is case sensitive so While is a valid class name). Line 8 is also valid because an equation may be placed in a String operation as shown.

Learn more problems on : Flow Control

Discuss about this problem : Discuss in Forum

2.

Which three statements are true?

  1. Assertion checking is typically enabled when a program is deployed.
  2. It is never appropriate to write code to handle failure of an assert statement.
  3. Assertion checking is typically enabled during program development and testing.
  4. Assertion checking can be selectively enabled or disabled on a per-package basis, but not on a per-class basis.
  5. Assertion checking can be selectively enabled or disabled on both a per-package basis and a per-class basis.

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

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

(1) is wrong. It's just not true.

(2) is correct. You're never supposed to handle an assertion failure.

(3) is correct. Assertions let you test your assumptions during development, but the assertion code—in effect—evaporates when the program is deployed, leaving behind no overhead or debugging code to track down and remove.

(4) is wrong. See the explanation for (5) below.

(5) is correct. Assertion checking can be selectively enabled or disabled on a per-package basis. Note that the package default assertion status determines the assertion status for classes initialized in the future that belong to the named package or any of its "subpackages".

The assertion status can be set for a named top-level class and any nested classes contained therein. This setting takes precedence over the class loader's default assertion status, and over any applicable per-package default. If the named class is not a top-level class, the change of status will have no effect on the actual assertion status of any class.

Learn more problems on : Assertions

Discuss about this problem : Discuss in Forum

3.

Which two of the following are legal declarations for nonnested classes and interfaces?

  1. final abstract class Test {}
  2. public static interface Test {}
  3. final public class Test {}
  4. protected abstract class Test {}
  5. protected interface Test {}
  6. abstract public class Test {}

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

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

(3), (6). Both are legal class declarations.

(1) is wrong because a class cannot be abstract and final—there would be no way to use such a class. (2) is wrong because interfaces and classes cannot be marked as static. (4) and (5) are wrong because classes and interfaces cannot be marked as protected.

Learn more problems on : Declarations and Access Control

Discuss about this problem : Discuss in Forum

4.

interface Base 
{
    boolean m1 ();
    byte m2(short s);
}
which two code fragments will compile?
  1. interface Base2 implements Base {}
  2. abstract class Class2 extends Base
    { public boolean m1(){ return true; }}
  3. abstract class Class2 implements Base {}
  4. abstract class Class2 implements Base
    { public boolean m1(){ return (7 > 4); }}
  5. abstract class Class2 implements Base
    { protected boolean m1(){ return (5 > 7) }}

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

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

(3) is correct because an abstract class doesn't have to implement any or all of its interface's methods. (4) is correct because the method is correctly implemented ((7 > 4) is a boolean).

(1) is incorrect because interfaces don't implement anything. (2) is incorrect because classes don't extend interfaces. (5) is incorrect because interface methods are implicitly public, so the methods being implemented must be public.

Learn more problems on : Declarations and Access Control

Discuss about this problem : Discuss in Forum

5.

Which of the following is/are legal method declarations?

  1. protected abstract void m1();
  2. static final void m1(){}
  3. synchronized public final void m1() {}
  4. private native void m1();

A.
1 and 3
B.
2 and 4
C.
1 only
D.
All of them are legal declarations.

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

All the given statements are legal declarations.

Learn more problems on : Declarations and Access Control

Discuss about this problem : Discuss in Forum

6.

What will be the output of the program?

class Happy extends Thread 
{ 
    final StringBuffer sb1 = new StringBuffer(); 
    final StringBuffer sb2 = new StringBuffer(); 

    public static void main(String args[]) 
    { 
        final Happy h = new Happy(); 

        new Thread() 
        { 
            public void run() 
            { 
                synchronized(this) 
                { 
                    h.sb1.append("A"); 
                    h.sb2.append("B"); 
                    System.out.println(h.sb1); 
                    System.out.println(h.sb2); 
                } 
            } 
        }.start(); 

        new Thread() 
        { 
            public void run() 
            { 
                synchronized(this) 
                { 
                    h.sb1.append("D"); 
                    h.sb2.append("C"); 
                    System.out.println(h.sb2); 
                    System.out.println(h.sb1); 
                } 
            } 
        }.start(); 
    } 
}

A.
ABBCAD
B.
ABCBCAD
C.
CDADACB
D.
Output determined by the underlying platform.

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

Can you guarantee the order in which threads are going to run? No you can't. So how do you know what the output will be? The output cannot be determined.

Learn more problems on : Threads

Discuss about this problem : Discuss in Forum

7.

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

8.

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

A.
hello throwit caught
B.
Compilation fails
C.
hello throwit RuntimeException caught after
D.
hello throwit caught finally after

Your Answer: Option (Not Answered)

Correct Answer: Option D

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.

Learn more problems on : Exceptions

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 allows the programmer to destroy an object x?

A.
x.delete()
B.
x.finalize()
C.
Runtime.getRuntime().gc()
D.
Only the garbage collection system can destroy an object.

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

Option D is correct. When an object is no longer referenced, it may be reclaimed by the garbage collector. If an object declares a finalizer, the finalizer is executed before the object is reclaimed to give the object a last chance to clean up resources that would not otherwise be released. When a class is no longer needed, it may be unloaded.

Option A is wrong. I found 4 delete() methods in all of the Java class structure. They are:

  1. delete() - Method in class java.io.File : Deletes the file or directory denoted by this abstract pathname.
  2. delete(int, int) - Method in class java.lang.StringBuffer : Removes the characters in a substring of this StringBuffer.
  3. delete(int, int) - Method in interface javax.accessibility.AccessibleEditableText : Deletes the text between two indices
  4. delete(int, int) - Method in class : javax.swing.text.JTextComponent.AccessibleJTextComponent; Deletes the text between two indices

None of these destroy the object to which they belong.

Option B is wrong. I found 19 finalize() methods. The most interesting, from this questions point of view, was the finalize() method in class java.lang.Object which is called by the garbage collector on an object when garbage collection determines that there are no more references to the object. This method does not destroy the object to which it belongs.

Option C is wrong. But it is interesting. The Runtime class has many methods, two of which are:

  1. getRuntime() - Returns the runtime object associated with the current Java application.
  2. gc() - Runs the garbage collector. Calling this method suggests that the Java virtual machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the virtual machine has made its best effort to recycle all discarded objects. Interesting as this is, it doesn't destroy the object.

Learn more problems on : Garbage Collections

Discuss about this problem : Discuss in Forum

11.

class Test 
{  
    private Demo d; 
    void start() 
    {  
        d = new Demo(); 
        this.takeDemo(d); /* Line 7 */
    } /* Line 8 */
    void takeDemo(Demo demo) 
    { 
        demo = null;  
        demo = new Demo(); 
    } 
}
When is the Demo object eligible for garbage collection?

A.
After line 7
B.
After line 8
C.
After the start() method completes
D.
When the instance running this code is made eligible for garbage collection.

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

Option D is correct. By a process of elimination.

Option A is wrong. The variable d is a member of the Test class and is never directly set to null.

Option B is wrong. A copy of the variable d is set to null and not the actual variable d.

Option C is wrong. The variable d exists outside the start() method (it is a class member). So, when the start() method finishes the variable d still holds a reference.

Learn more problems on : Garbage Collections

Discuss about this problem : Discuss in Forum

12.

What will be the output of the program?

public class Test 
{
    public static void main(String [] args) 
    {
        int I = 1;
        do while ( I < 1 )
        System.out.print("I is " + I);
        while ( I > 1 ) ;
    }
}

A.
I is 1
B.
I is 1 I is 1
C.
No output is produced.
D.
Compilation error

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

There are two different looping constructs in this problem. The first is a do-while loop and the second is a while loop, nested inside the do-while. The body of the do-while is only a single statement-brackets are not needed. You are assured that the while expression will be evaluated at least once, followed by an evaluation of the do-while expression. Both expressions are false and no output is produced.

Learn more problems on : Flow Control

Discuss about this problem : Discuss in Forum

13.

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

14.

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

A.
AAACCC
B.
AAADDD
C.
BBBCCC
D.
BBBDDD

Your Answer: Option (Not Answered)

Correct Answer: Option A

Learn more problems on : Java.lang Class

Discuss about this problem : Discuss in Forum

15.

What will be the output of the program?

class A 
{ 
    public A(int x){} 
} 
class B extends A { } 
public class test 
{ 
    public static void main (String args []) 
    {
        A a = new B(); 
        System.out.println("complete"); 
    } 
}

A.
It compiles and runs printing nothing
B.
Compiles but fails at runtime
C.
Compile Error
D.
Prints "complete"

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

No constructor has been defined for class B therefore it will make a call to the default constructor but since class B extends class A it will also call the Super() default constructor.

Since a constructor has been defined in class A java will no longer supply a default constructor for class A therefore when class B calls class A's default constructor it will result in a compile error.

Learn more problems on : Java.lang Class

Discuss about this problem : Discuss in Forum

16.

What will be the output of the program?

String x = "xyz";
x.toUpperCase(); /* Line 2 */
String y = x.replace('Y', 'y');
y = y + "abc";
System.out.println(y);

A.
abcXyZ
B.
abcxyz
C.
xyzabc
D.
XyZabc

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

Line 2 creates a new String object with the value "XYZ", but this new object is immediately lost because there is no reference to it. Line 3 creates a new String object referenced by y. This new String object has the value "xyz" because there was no "Y" in the String object referred to by x. Line 4 creates a new String object, appends "abc" to the value "xyz", and refers y to the result.

Learn more problems on : Java.lang Class

Discuss about this problem : Discuss in Forum

17.

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

18.

What will be the output of the program?

class Tree { } 
class Pine extends Tree { } 
class Oak extends Tree { } 
public class Forest1 
{ 
    public static void main (String [] args)
    { 
        Tree tree = new Pine(); 
        if( tree instanceof Pine ) 
            System.out.println ("Pine"); 
        else if( tree instanceof Tree ) 
            System.out.println ("Tree"); 
        else if( tree instanceof Oak ) 
            System.out.println ( "Oak" ); 
        else 
            System.out.println ("Oops "); 
    } 
}

A.
Pine
B.
Tree
C.
Forest
D.
Oops

Your Answer: Option (Not Answered)

Correct Answer: Option A

Explanation:

The program prints "Pine".

Learn more problems on : Java.lang Class

Discuss about this problem : Discuss in Forum

19.

What will be the output of the program?

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

    void start() 
    {
        int a = 3;
        int b = 4;
        System.out.print(" " + 7 + 2 + " ");
        System.out.print(a + b);
        System.out.print(" " + a + b + " ");
        System.out.print(foo() + a + b + " ");
        System.out.println(a + b + foo());
    }

    String foo() 
    {
        return "foo";
    }
}

A.
9 7 7 foo 7 7foo
B.
72 34 34 foo34 34foo
C.
9 7 7 foo34 34foo
D.
72 7 34 foo34 7foo

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

Because all of these expressions use the + operator, there is no precedence to worry about and all of the expressions will be evaluated from left to right. If either operand being evaluated is a String, the + operator will concatenate the two operands; if both operands are numeric, the + operator will add the two operands.

Learn more problems on : Operators and Assignments

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.