Online Java Programming Test - Java Programming Test - Random

Instruction:

  • This is a FREE online test. Beware of scammers who ask for money to attend this test.
  • Total number of questions: 20.
  • Time allotted: 30 minutes.
  • Each question carries 1 mark; there are no negative marks.
  • DO NOT refresh the page.
  • All the best!

Marks : 2/20


Total number of questions
20
Number of answered questions
0
Number of unanswered questions
20
Test Review : View answers and explanation for this test.

1.
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);
    }
}
0
1
2
Compilation fails.
Your Answer: Option
(Not Answered)
Correct Answer: Option
Explanation:

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


2.
/* 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;
1 only
2 and 5
3 and 4
3 and 5
Your Answer: Option
(Not Answered)
Correct Answer: Option
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.


3.
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.println(i); 
    } 
}
2
4
8
16
Your Answer: Option
(Not Answered)
Correct Answer: Option
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.


4.
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;
1 and 2
2 and 3
3 and 4
All statements are correct.
Your Answer: Option
(Not Answered)
Correct Answer: Option
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.


5.
What will be the output of the program?
for (int i = 0; i < 4; i += 2) 
{ 
    System.out.print(i + " "); 
} 
System.out.println(i); /* Line 5 */
0 2 4
0 2 4 5
0 1 2 3 4
Compilation fails.
Your Answer: Option
(Not Answered)
Correct Answer: Option
Explanation:

Compilation fails on the line 5 - System.out.println(i); as the variable i has only been declared within the for loop. It is not a recognised variable outside the code block of loop.


6.
What will be the output of the program?
public class Switch2 
{
    final static short x = 2;
    public static int y = 0;
    public static void main(String [] args) 
    {
        for (int z=0; z < 3; z++) 
        {
            switch (z) 
            {
                case y: System.out.print("0 ");   /* Line 11 */
                case x-1: System.out.print("1 "); /* Line 12 */
                case x: System.out.print("2 ");   /* Line 13 */
            }
        }
    }
}
0 1 2
0 1 2 1 2 2
Compilation fails at line 11.
Compilation fails at line 12.
Your Answer: Option
(Not Answered)
Correct Answer: Option
Explanation:

Case expressions must be constant expressions. Since x is marked final, lines 12 and 13 are legal; however y is not a final so the compiler will fail at line 11.


7.
What will be the output of the program?
int x = 3; 
int y = 1; 
if (x = y) /* Line 3 */
{
    System.out.println("x =" + x); 
}
x = 1
x = 3
Compilation fails.
The code runs with no output.
Your Answer: Option
(Not Answered)
Correct Answer: Option
Explanation:

Line 3 uses an assignment as opposed to comparison. Because of this, the if statement receives an integer value instead of a boolean. And so the compilation fails.


8.
What will be the output of the program?
public class Switch2 
{
    final static short x = 2;
    public static int y = 0;
    public static void main(String [] args) 
    {
        for (int z=0; z < 3; z++) 
        {
            switch (z) 
            {
                case x: System.out.print("0 ");
                case x-1: System.out.print("1 ");
                case x-2: System.out.print("2 ");
            }
        }
    }
}
0 1 2
0 1 2 1 2 2
2 1 0 1 0 0
2 1 2 0 1 2
Your Answer: Option
(Not Answered)
Correct Answer: Option
Explanation:

The case expressions are all legal because x is marked final, which means the expressions can be evaluated at compile time. In the first iteration of the for loop case x-2 matches, so 2 is printed. In the second iteration, x-1 is matched so 1 and 2 are printed (remember, once a match is found all remaining statements are executed until a break statement is encountered). In the third iteration, x is matched. So 0 1 and 2 are printed.


9.
What is the numerical range of char?
0 to 32767
0 to 65535
-256 to 255
-32768 to 32767
Your Answer: Option
(Not Answered)
Correct Answer: Option
Explanation:

The char type is integral but unsigned. The range of a variable of type char is from 0 to 216-1 or 0 to 65535. Java characters are Unicode, which is a 16-bit encoding capable of representing a wide range of international characters. If the most significant nine bits of a char are 0, then the encoding is the same as seven-bit ASCII.


10.
Suppose that you would like to create an instance of a new Map that has an iteration order that is the same as the iteration order of an existing instance of a Map. Which concrete implementation of the Map interface should be used for the new instance?
TreeMap
HashMap
LinkedHashMap
The answer depends on the implementation of the existing instance.
Your Answer: Option
(Not Answered)
Correct Answer: Option
Explanation:

The iteration order of a Collection is the order in which an iterator moves through the elements of the Collection. The iteration order of a LinkedHashMap is determined by the order in which elements are inserted.

When a new LinkedHashMap is created by passing a reference to an existing Collection to the constructor of a LinkedHashMap the Collection.addAll method will ultimately be invoked.

The addAll method uses an iterator to the existing Collection to iterate through the elements of the existing Collection and add each to the instance of the new LinkedHashMap.

Since the iteration order of the LinkedHashMap is determined by the order of insertion, the iteration order of the new LinkedHashMap must be the same as the interation order of the old Collection.


11.
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() + " " );
}
one two three four
four three two one
four one three two
one two three four one
Your Answer: Option
(Not Answered)
Correct Answer: Option
Explanation:

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


12.
Which statement is true for the class java.util.HashSet?
The elements in the collection are ordered.
The collection is guaranteed to be immutable.
The elements in the collection are guaranteed to be unique.
The elements in the collection are accessed using a unique key.
Your Answer: Option
(Not Answered)
Correct Answer: Option
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.


13.
Which two of the following methods are defined in class Thread?
  1. start()
  2. wait()
  3. notify()
  4. run()
  5. terminate()
1 and 4
2 and 3
3 and 4
2 and 4
Your Answer: Option
(Not Answered)
Correct Answer: Option
Explanation:

(1) and (4). Only start() and run() are defined by the Thread class.

(2) and (3) are incorrect because they are methods of the Object class. (5) is incorrect because there's no such method in any thread-related class.


14.
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(); 
    } 
}
DeadLock
It print 12 12 12 12
Compilation Error
Cannot determine output.
Your Answer: Option
(Not Answered)
Correct Answer: Option
Explanation:

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


15.
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?
after line 5
after line 6
after line 7
There is no way to be absolutely certain.
Your Answer: Option
(Not Answered)
Correct Answer: Option

16.
class HappyGarbage01 
{ 
    public static void main(String args[]) 
    {
        HappyGarbage01 h = new HappyGarbage01(); 
        h.methodA(); /* Line 6 */
    } 
    Object methodA() 
    {
        Object obj1 = new Object(); 
        Object [] obj2 = new Object[1]; 
        obj2[0] = obj1; 
        obj1 = null; 
        return obj2[0]; 
    } 
}
Where will be the most chance of the garbage collector being invoked?
After line 9
After line 10
After line 11
Garbage collector never invoked in methodA()
Your Answer: Option
(Not Answered)
Correct Answer: Option
Explanation:

Option D is correct. Garbage collection takes place after the method has returned its reference to the object. The method returns to line 6, there is no reference to store the return value. so garbage collection takes place after line 6.

Option A is wrong. Because the reference to obj1 is stored in obj2[0]. The Object obj1 still exists on the heap and can be accessed by an active thread through the reference stored in obj2[0].

Option B is wrong. Because it is only one of the references to the object obj1, the other reference is maintained in obj2[0].

Option C is wrong. The garbage collector will not be called here because a reference to the object is being maintained and returned in obj2[0].


17.
Which statement is true about assertions in the Java programming language?
Assertion expressions should not contain side effects.
Assertion expression values can be any primitive type.
Assertions should be used for enforcing preconditions on public methods.
An AssertionError thrown as a result of a failed assertion should always be handled by the enclosing method.
Your Answer: Option
(Not Answered)
Correct Answer: Option
Explanation:

Option A is correct. Because assertions may be disabled, programs must not assume that the boolean expressions contained in assertions will be evaluated. Thus these expressions should be free of side effects. That is, evaluating such an expression should not affect any state that is visible after the evaluation is complete. Although it is not illegal for a boolean expression contained in an assertion to have a side effect, it is generally inappropriate, as it could cause program behaviour to vary depending on whether assertions are enabled or disabled.

Assertion checking may be disabled for increased performance. Typically, assertion checking is enabled during program development and testing and disabled for deployment.

Option B is wrong. Because you assert that something is "true". True is Boolean. So, an expression must evaluate to Boolean, not int or byte or anything else. Use the same rules for an assertion expression that you would use for a while condition.

Option C is wrong. Usually, enforcing a precondition on a public method is done by condition-checking code that you write yourself, to give you specific exceptions.

Option D is wrong. "You're never supposed to handle an assertion failure"

Not all legal uses of assertions are considered appropriate. As with so much of Java, you can abuse the intended use for assertions, despite the best efforts of Sun's Java engineers to discourage you. For example, you're never supposed to handle an assertion failure. That means don't catch it with a catch clause and attempt to recover. Legally, however, AssertionError is a subclass of Throwable, so it can be caught. But just don't do it! If you're going to try to recover from something, it should be an exception. To discourage you from trying to substitute an assertion for an exception, the AssertionError doesn't provide access to the object that generated it. All you get is the String message.


18.
What will be the output of the program?
public class StringRef 
{
    public static void main(String [] args) 
    {
        String s1 = "abc";
        String s2 = "def";
        String s3 = s2;   /* Line 7 */
        s2 = "ghi";
        System.out.println(s1 + s2 + s3);
    }
}
abcdefghi
abcdefdef
abcghidef
abcghighi
Your Answer: Option
(Not Answered)
Correct Answer: Option
Explanation:

After line 7 executes, both s2 and s3 refer to a String object that contains the value "def". When line 8 executes, a new String object is created with the value "ghi", to which s2 refers. The reference variable s3 still refers to the (immutable) String object with the value "def".


19.
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"); 
        } 
    } 
}
AAACCC
AAADDD
BBBCCC
BBBDDD
Your Answer: Option
(Not Answered)
Correct Answer: Option

20.

Which statement is true given the following?

Double d = Math.random();

0.0 < d <= 1.0
0.0 <= d < 1.0
Compilation fail
Cannot say.
Your Answer: Option
(Not Answered)
Correct Answer: Option
Explanation:

The Math.random() method returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0


*** END OF THE TEST ***
Time Left: 00:29:56
Post your test result / feedback here: