Would you like to submit the test?

Java Questions And Answers Sample Test 4


Sample Java Test 4 for you to Practice. Evaluate your Java Test 4 test answering skills by trying the online Java Sample Test 4 and know your score.

Java Test 4


You have scored 3 out of 10
You Scored:2
Total Questions:2
Attended Questions:2
Correct Answered:2
1. Which method registers a thread in a thread scheduler?



Explanation:

Option C 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. 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 B is wrong. There is no construct() method in the Thread class.

Option D is wrong. There is no register() method in the Thread class.


2.
Which three are methods of the Object class?

notify();
notifyAll();
isInterrupted();
synchronized();
interrupt();
wait(long msecs);
sleep(long msecs);
yield();



Explanation:

(1), (2), and (6) are correct. They are all related to the list of threads waiting on the specified object.

(3), (5), (7), and (8) are incorrect answers. The methods isInterrupted() and interrupt() are instance methods of Thread.

The methods sleep() and yield() are static methods of Thread.

D is incorrect because synchronized is a keyword and the synchronized() construct is part of the Java language.


3.
switch(x) 
    default:  
        System.out.println("Hello"); 
}
Which two are acceptable types for x?
byte
long
char
float
Short
Long



Explanation:

Switch statements are based on integer expressions and since both bytes and chars can implicitly be widened to an integer, these can also be used. Also shorts can be used. Short and Long are wrapper classes and reference types can not be used as variables.


4.
What will be the output of the program?

class Bitwise 
{
    public static void main(String [] args) 
    {
        int x = 11 & 9;
        int y = x ^ 3;
        System.out.println( y | 12 );
    }
}



Explanation:

The & operator produces a 1 bit when both bits are 1. The result of the & operation is 9. The ^ operator produces a 1 bit when exactly one bit is 1; the result of this operation is 10. The | operator produces a 1 bit when at least one bit is 1; the result of this operation is 14.


5.
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?



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.

View Answer Workspace Report Discuss in Forum



Read more:
Assertions - Pointing out the correct statements
Assertions - Pointing out the errors



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

yield()
wait()
notify()
notifyAll()
sleep(1000)
aLiveThread.join()
Thread.killThread()



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.


7. Which class does not override the equals() and hashCode() methods, inheriting them directly from class Object?



Explanation:

java.lang.StringBuffer is the only class in the list that uses the default methods provided by class Object.


8. What is the numerical range of char?



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.


9. 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?



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.


10. Which collection class allows you to grow or shrink its size and provides indexed access to its elements, but whose methods are not synchronized?



Explanation:

All of the collection classes allow you to grow or shrink the size of your collection. ArrayList provides an index to its elements. The newer collection classes tend not to have synchronized methods. Vector is an older implementation of ArrayList functionality and has synchronized methods; it is slower than ArrayList.


11. Which is a valid keyword in java?



Explanation:

interface is a valid keyword.

Option B is wrong because although "String" is a class type in Java, "string" is not a keyword.

Option C is wrong because "Float" is a class type. The keyword for the Java primitive is float.

Option D is wrong because "unsigned" is a keyword in C/C++ but not in Java.


12.
What will be the output of the program?

public class SwitchTest 
{  
    public static void main(String[] args) 
    {
        System.out.println("value =" + switchIt(4)); 
    } 
    public static int switchIt(int x) 
    {
        int j = 1;  
        switch (x) 
        { 
            case l: j++; 
            case 2: j++;  
            case 3: j++; 
            case 4: j++; 
            case 5: j++; 
            default: j++; 
            } 
        return j + x;  
    } 
}



Explanation:

Because there are no break statements, once the desired result is found, the program continues though each of the remaining options.


13.
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?



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.


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



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.


15.
What will be the output of the program?

int i = l, j = -1; 
switch (i) 
{
    case 0, 1: j = 1; /* Line 4 */
    case 2: j = 2; 
    default: j = 0; 
System.out.println("j = " + j); 



Explanation:

The case statement takes only a single argument. The case statement on line 4 is given two arguments so the compiler complains.


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



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.


17.
What will be the output of the program?

class Test 
{
    static int s;
    public static void main(String [] args) 
    {
        Test p = new Test();
        p.start();
        System.out.println(s);
    }

    void start() 
    {
        int x = 7;
        twice(x);
        System.out.print(x + " ");
    }

    void twice(int x) 
    {
        x = x*2;
        s = x;
    }
}



Explanation:

The int x in the twice() method is not the same int x as in the start() method. Start()'s x is not affected by the twice() method. The instance variable s is updated by twice()'s x, which is 14.


18.
public void test(int x) 
    int odd = 1; 
    if(odd) /* Line 4 */
    {
        System.out.println("odd"); 
    } 
    else 
    {
        System.out.println("even"); 
    } 
}
Which statement is true?



Explanation:

The compiler will complain because of incompatible types (line 4), the if expects a boolean but it gets an integer.


19. Which one of these lists contains only Java programming language keywords?



Explanation:

All the words in option B are among the 49 Java keywords. Although goto reserved as a keyword in Java, goto is not used and has no function.

Option A is wrong because the keyword for the primitive int starts with a lowercase i.

Option C is wrong because "virtual" is a keyword in C++, but not Java.

Option D is wrong because "constant" is not a keyword. Constants in Java are marked static and final.

Option E is wrong because "include" is a keyword in C, but not in Java.


20.
Which two of the following methods are defined in class Thread?

start()
wait()
notify()
run()
terminate()



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.


21.
public class X 
{
    public static void main(String [] args) 
    {
        X x = new X();
        X x2 = m1(x); /* Line 6 */
        X x4 = new X();
        x2 = x4; /* Line 8 */
        doComplexStuff();
    }
    static X m1(X mx) 
    {
        mx = new X();
        return mx;
    }
}
After line 8 runs. how many objects are eligible for garbage collection?



Explanation:

By the time line 8 has run, the only object without a reference is the one generated as a result of line 6. Remember that "Java is pass by value," so the reference variable x is not affected by the m1() method.


22.
Which three are valid declarations of a char?

char c1 = 064770;
char c2 = 'face';
char c3 = 0xbeef;
char c4 = u0022;
char c5 = 'iface';
char c6 = 'uface';



Explanation:

(1), (3), and (6) are correct. char c1 = 064770; is an octal representation of the integer value 27128, which is legal because it fits into an unsigned 16-bit integer. char c3 = 0xbeef; is a hexadecimal representation of the integer value 48879, which fits into an unsigned 16-bit integer. char c6 = 'uface'; is a Unicode representation of a character.

char c2 = 'face'; is wrong because you can't put more than one character in a char literal. The only other acceptable char literal that can go between single quotes is a Unicode value, and Unicode literals must always start with a 'u'.

char c4 = u0022; is wrong because the single quotes are missing.

char c5 = 'iface'; is wrong because it appears to be a Unicode representation (notice the backslash), but starts with 'i' rather than 'u'.


23.
class X implements Runnable 
    public static void main(String args[]) 
    {
        /* Missing code? */
    } 
    public void run() {} 
}
Which of the following line of code is suitable to start a thread ?





24.
public Object m() 
{  
    Object o = new Float(3.14F); 
    Object [] oa = new Object[l];
    oa[0] = o; /* Line 5 */
    o = null;  /* Line 6 */
    oa[0] = null; /* Line 7 */
    return o; /* Line 8 */
}
When is the Float object, created in line 3, eligible for garbage collection?



Explanation:

Option A is wrong. This simply copies the object reference into the array.

Option B is wrong. The reference o is set to null, but, oa[0] still maintains the reference to the Float object.

Option C is correct. The thread of execution will then not have access to the object.


25. You need to store elements in a collection that guarantees that no duplicates are stored and all elements can be accessed in natural order. Which interface provides that capability?



Explanation:

Option B is correct. A set is a collection that contains no duplicate elements. The iterator returns the elements in no particular order (unless this set is an instance of some class that provides a guarantee). A map cannot contain duplicate keys but it may contain duplicate values. List and Collection allow duplicate elements.

Option A is wrong. A map is an object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value. The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order (ascending key order); others, like the HashMap class, do not (does not guarantee that the order will remain constant over time).

Option C is wrong. A list is an ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list. Unlike sets, lists typically allow duplicate elements.

Option D is wrong. A collection is also known as a sequence. The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list. Unlike sets, lists typically allow duplicate elements.


26. Which statement is true?



Explanation:

Option A is correct. 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.

Option B is wrong. Is there such a thing as conditional compilation in Java?

Option C is wrong. For private methods - yes. But do not use assertions to check the parameters of a public method. An assert is inappropriate in public methods because the method guarantees that it will always enforce the argument checks. A public method must check its arguments whether or not assertions are enabled. Further, the assert construct does not throw an exception of the specified type. It can throw only an AssertionError.

Option D is wrong. Because you're never supposed to handle an assertion failure. That means don't catch it with a catch clause and attempt to recover.


27. Which is true about a method-local inner class?



Explanation:

Option B is correct because a method-local inner class can be abstract, although it means a subclass of the inner class must be created if the abstract class is to be used (so an abstract method-local inner class is probably not useful).

Option A is incorrect because a method-local inner class does not have to be declared final (although it is legal to do so).

C and D are incorrect because a method-local inner class cannot be made public (remember-you cannot mark any local variables as public), or static.


28.
public interface Foo 
    int k = 4; /* Line 3 */
}
Which three piece of codes are equivalent to line 3?
final int k = 4;
public int k = 4;
static int k = 4;
abstract int k = 4;
volatile int k = 4;
protected int k = 4;



Explanation:

(1), (2) and (3) are correct. Interfaces can have constants, which are always implicitly public, static, and final. Interface constant declarations of public, static, and final are optional in any combination.


29. Which class or interface defines the wait(), notify(),and notifyAll() methods?



Explanation:

The Object class defines these thread-specific methods.

Option B, C, and D are incorrect because they do not define these methods. And yes, the Java API does define a class called Class, though you do not need to know it for the exam.


30.
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?



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.




FreshersLive - No.1 Job site in India. Here you can find latest 2017 government as well as private job recruitment notifications for different posts vacancies in India. Get top company jobs for both fresher and experienced. Job Seekers can get useful interview tips, resume services & interview Question and answer. Practice online test free which is helpful for interview preparation. Register with us to get latest employment news/rojgar samachar notifications. Also get latest free govt and other sarkari naukri job alerts daily through E-mail.