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


2.

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


3.

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


4.

What will be the output of the program?

String x = new String("xyz");
String y = "abc";
x = x + y;
How many String objects have been created?

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

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

Line 1 creates two, one referred to by x and the lost String "xyz". Line 2 creates one (for a total of three). Line 3 creates one more (for a total of four), the concatenated String referred to by x with a value of "xyzabc".

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 X 
{  
    public static void main(String [] args) 
    {
        try 
        {
            badMethod(); /* Line 7 */
            System.out.print("A"); 
        } 
        catch (Exception ex) /* Line 10 */
        {
            System.out.print("B"); /* Line 12 */
        } 
        finally /* Line 14 */
        {
            System.out.print("C"); /* Line 16 */
        }  
        System.out.print("D"); /* Line 18 */
    } 
    public static void badMethod() 
    {
        throw new RuntimeException(); 
    } 
}

A.
AB
B.
BC
C.
ABC
D.
BCD

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

(1) A RuntimeException is thrown, this is a subclass of exception.

(2) The exception causes the try to complete abruptly (line 7) therefore line 8 is never executed.

(3) The exception is caught (line 10) and "B" is output (line 12)

(4) The finally block (line 14) is always executed and "C" is output (line 16).

(5) The exception was caught, so the program continues with line 18 and outputs "D".

Learn more problems on : Exceptions

Discuss about this problem : Discuss in Forum


6.

/* Missing statements ? */
public class NewTreeSet extends java.util.TreeSet
{
    public static void main(String [] args) 
    {
        java.util.TreeSet t = new java.util.TreeSet();
        t.clear();
    }
    public void clear() 
    {
        TreeMap m = new TreeMap();
        m.clear();
    }
}
which two statements, added independently at beginning of the program, allow the code to compile?
  1. No statement is required
  2. import java.util.*;
  3. import.java.util.Tree*;
  4. import java.util.TreeSet;
  5. import java.util.TreeMap;

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

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

(2) and (5). TreeMap is the only class that must be imported. TreeSet does not need an import statement because it is described with a fully qualified name.

(1) is incorrect because TreeMap must be imported. (3) is incorrect syntax for an import statement. (4) is incorrect because it will not import TreeMap, which is required.

Learn more problems on : Declarations and Access Control

Discuss about this problem : Discuss in Forum


7.

System.out.print("Start ");
try 
{
    System.out.print("Hello world");
    throw new FileNotFoundException();
}
System.out.print(" Catch Here "); /* Line 7 */
catch(EOFException e) 
{
    System.out.print("End of file exception");
}
catch(FileNotFoundException e) 
{
    System.out.print("File not found");
}
and given that EOFException and FileNotFoundException are both subclasses of IOException, and further assuming this block of code is placed into a class, which statement is most true concerning this code?

A.
The code will not compile.
B.
Code output: Start Hello world File Not Found.
C.
Code output: Start Hello world End of file exception.
D.
Code output: Start Hello world Catch Here File not found.

Your Answer: Option (Not Answered)

Correct Answer: Option A

Explanation:

Line 7 will cause a compiler error. The only legal statements after try blocks are either catch or finally statements.

Option B, C, and D are incorrect based on the program logic described above. If line 7 was removed, the code would compile and the correct answer would be Option B.

Learn more problems on : Exceptions

Discuss about this problem : Discuss in Forum


8.

Which of the following class level (nonlocal) variable declarations will not compile?

A.
protected int a;
B.
transient int b = 3;
C.
private synchronized int e;
D.
volatile int d;

Your Answer: Option (Not Answered)

Correct Answer: Option C

Explanation:

Option C will not compile; the synchronized modifier applies only to methods.

Option A and B will compile because protected and transient are legal variable modifiers. Option D will compile because volatile is a proper variable modifier.

Learn more problems on : Declarations and Access Control

Discuss about this problem : Discuss in Forum


9.

Which cause a compiler error?

A.
int[ ] scores = {3, 5, 7};
B.
int [ ][ ] scores = {2,7,6}, {9,3,45};
C.
String cats[ ] = {"Fluffy", "Spot", "Zeus"};
D.
boolean results[ ] = new boolean [] {true, false, true};
E.
Integer results[ ] = {new Integer(3), new Integer(5), new Integer(8)};

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

Option B generates a compiler error: <identifier> expected. The compiler thinks you are trying to create two arrays because there are two array initialisers to the right of the equals, whereas your intention was to create one 3 x 3 two-dimensional array.

To correct the problem and make option B compile you need to add an extra pair of curly brackets:

int [ ] [ ] scores = { {2,7,6}, {9,3,45} };

Learn more problems on : Declarations and Access Control

Discuss about this problem : Discuss in Forum


10.

What will be the output of the program?

public class ArrayTest 
{ 
    public static void main(String[ ] args)
    { 
        float f1[ ], f2[ ]; 
        f1 = new float[10]; 
        f2 = f1; 
        System.out.println("f2[0] = " + f2[0]); 
    } 
}

A.
It prints f2[0] = 0.0
B.
It prints f2[0] = NaN
C.
An error at f2 = f1; causes compile to fail.
D.
It prints the garbage value.

Your Answer: Option (Not Answered)

Correct Answer: Option A

Explanation:

Option A is correct. When you create an array (f1 = new float[10];) the elements are initialises to the default values for the primitive data type (float in this case - 0.0), so f1 will contain 10 elements each with a value of 0.0. f2 has been declared but has not been initialised, it has the ability to reference or point to an array but as yet does not point to any array. f2 = f1; copies the reference (pointer/memory address) of f1 into f2 so now f2 points at the array pointed to by f1.

This means that the values returned by f2 are the values returned by f1. Changes to f1 are also changes to f2 because both f1 and f2 point to the same array.

Learn more problems on : Declarations and Access Control

Discuss about this problem : Discuss in Forum


11.

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


12.

What will be the output of the program?

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

    void start() 
    {
        String s1 = "slip";
        String s2 = fix(s1);
        System.out.println(s1 + " " + s2);
    }

    String fix(String s1) 
    {
        s1 = s1 + "stream";
        System.out.print(s1 + " ");
        return "stream";
    }
}

A.
slip stream
B.
slipstream stream
C.
stream slip stream
D.
slipstream slip stream

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

When the fix() method is first entered, start()'s s1 and fix()'s s1 reference variables both refer to the same String object (with a value of "slip"). Fix()'s s1 is reassigned to a new object that is created when the concatenation occurs (this second String object has a value of "slipstream"). When the program returns to start(), another String object is created, referred to by s2 and with a value of "stream".

Learn more problems on : Operators and Assignments

Discuss about this problem : Discuss in Forum


13.

What will be the output of the program?

class BitShift 
{
    public static void main(String [] args) 
    {
        int x = 0x80000000;
        System.out.print(x + " and  ");
        x = x >>> 31;
        System.out.println(x);
    }
}

A.
-2147483648 and 1
B.
0x80000000 and 0x00000001
C.
-2147483648 and -1
D.
1 and -2147483648

Your Answer: Option (Not Answered)

Correct Answer: Option A

Explanation:

Option A is correct. The >>> operator moves all bits to the right, zero filling the left bits. The bit transformation looks like this:

Before: 1000 0000 0000 0000 0000 0000 0000 0000

After: 0000 0000 0000 0000 0000 0000 0000 0001

Option C is incorrect because the >>> operator zero fills the left bits, which in this case changes the sign of x, as shown.

Option B is incorrect because the output method print() always displays integers in base 10.

Option D is incorrect because this is the reverse order of the two output numbers.

Learn more problems on : Operators and Assignments

Discuss about this problem : Discuss in Forum


14.

What will be the output of the program?

public abstract class AbstractTest 
{
    public int getNum() 
    {
        return 45;
    }
    public abstract class Bar 
    {
        public int getNum() 
        {
            return 38;
        }
    }
    public static void main (String [] args) 
    {
        AbstractTest t = new AbstractTest() 
        {
            public int getNum() 
            {
                return 22;
            }
        };
        AbstractTest.Bar f = t.new Bar() 
        {
            public int getNum() 
            {
                return 57;
            }
        };
        
        System.out.println(f.getNum() + " " + t.getNum());
    }
}

A.
57 22
B.
45 38
C.
45 57
D.
An exception occurs at runtime.

Your Answer: Option (Not Answered)

Correct Answer: Option A

Explanation:

You can define an inner class as abstract, which means you can instantiate only concrete subclasses of the abstract inner class. The object referenced by the variable t is an instance of an anonymous subclass of AbstractTest, and the anonymous class overrides the getNum() method to return 22. The variable referenced by f is an instance of an anonymous subclass of Bar, and the anonymous Bar subclass also overrides the getNum() method (to return 57). Remember that to instantiate a Bar instance, we need an instance of the enclosing AbstractTest class to tie to the new Bar inner class instance. AbstractTest can't be instantiated because it's abstract, so we created an anonymous subclass (non-abstract) and then used the instance of that anonymous subclass to tie to the new Bar subclass instance.

Learn more problems on : Inner Classes

Discuss about this problem : Discuss in Forum


15.

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


16.

What will be the output of the program?

public class Test 
{ 
    public static void main (String[] args) 
    {
        String foo = args[1]; 
        String bar = args[2]; 
        String baz = args[3]; 
        System.out.println("baz = " + baz); /* Line 8 */
    } 
}

And the command line invocation:

> java Test red green blue

A.
baz =
B.
baz = null
C.
baz = blue
D.
Runtime Exception

Your Answer: Option (Not Answered)

Correct Answer: Option D

Explanation:

When running the program you entered 3 arguments "red", "green" and "blue". When dealing with arrays in java you must remember ALL ARRAYS IN JAVA ARE ZERO BASED therefore args[0] becomes "red", args[1] becomes "green" and args[2] becomes "blue".

When the program entcounters line 8 above at runtime it looks for args[3] which has never been created therefore you get an

ArrayIndexOutOfBoundsException at runtime.

Learn more problems on : Objects and Collections

Discuss about this problem : Discuss in Forum


17.

Which of the following statements is true?

A.
In an assert statement, the expression after the colon ( : ) can be any Java expression.
B.
If a switch block has no default, adding an assert default is considered appropriate.
C.
In an assert statement, if the expression after the colon ( : ) does not have a value, the assert's error message will be empty.
D.
It is appropriate to handle assertion failures using a catch clause.

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

Adding an assertion statement to a switch statement that previously had no default case is considered an excellent use of the assert mechanism.

Option A is incorrect because only Java expressions that return a value can be used. For instance, a method that returns void is illegal.

Option C is incorrect because the expression after the colon must have a value.

Option D is incorrect because assertions throw errors and not exceptions, and assertion errors do cause program termination and should not be handled.

Learn more problems on : Assertions

Discuss about this problem : Discuss in Forum


18.

Which is the valid declarations within an interface definition?

A.
public double methoda();
B.
public final double methoda();
C.
static void methoda(double d1);
D.
protected void methoda(double d1);

Your Answer: Option (Not Answered)

Correct Answer: Option A

Explanation:

Option A is correct. A public access modifier is acceptable. The method prototypes in an interface are all abstract by virtue of their declaration, and should not be declared abstract.

Option B is wrong. The final modifier means that this method cannot be constructed in a subclass. A final method cannot be abstract.

Option C is wrong. static is concerned with the class and not an instance.

Option D is wrong. protected is not permitted when declaring a method of an interface. See information below.

Member declarations in an interface disallow the use of some declaration modifiers; you cannot use transient, volatile, or synchronized in a member declaration in an interface. Also, you may not use the private and protected specifiers when declaring members of an interface.

Learn more problems on : Language Fundamentals

Discuss about this problem : Discuss in Forum


19.

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


20.

What is the name of the method used to start a thread execution?

A.
init();
B.
start();
C.
run();
D.
resume();

Your Answer: Option (Not Answered)

Correct Answer: Option B

Explanation:

Option B is Correct. The start() method causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

Option A is wrong. There is no init() method in the Thread class.

Option C is wrong. The run() method of a thread is like the main() method to an application. Starting the thread causes the object's run method to be called in that separately executing thread.

Option D is wrong. The resume() method is deprecated. It resumes a suspended 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.