Elance CORE JAVA Test Answers 2015



Which one of the following is NOT a reserved word in Java?
virtual
public
private
final


Which one of the following statements is true about Java Beans?
Java Beans are user defined classes.
All Java Beans must extend the java.bean base class
Java Beans cannot be used in server side programming, they are only used for Graphical User Interfaces.
Java Beans are not permitted to create any threads


What method should you always override when you have overridden the equals() method?
wait()
toString()
hashCode()
clone()


Which of these are advantages of encapsulation in Java?
Encapsulation in Java makes unit testing easy
Encapsulation reduces coupling of modules and increase cohesion inside a module
Encapsulated code is easy to change with new requirements
All of these


The Core Java platform provides many benefits to developers, including:
Superior speed and performance compared to native code
Direct compilation to native code on most platforms
A consistent programming interface across multiple hardware platforms
A purely functional programming language with a minimalist design philosophy


The Thread.sleep() method:
Causes all threads to suspend execution
Suspends execution in synchronized methods only
Causes the current thread to suspend execution
Causes the hosted virtual machine to suspend all forms of execution


To document an API, which tool do you use?
javaApi
documentcreate
javadoc
apicreate


To define a child class from the Parent class following is used:
class Child extends Parent
class Child extends Public Parent
class Child : Parent
class Child :: Parent


If we want a class not to be overridden,the class must be done as
Class should be abstract
Class should be final
Class should public
Class should be static


Java handles memory allocation and reuse using a process called:
Virtual Memory
Buddy Blocks
Manual Memory Management
Garbage Collection


Which additional keyword may be used with try-catch blocks?
finally
finish
finalize
final


The "javac" command line tool is used to:
Convert java bytecode files into native executables
Compile java source files into bytecode class files
Generate C headers and stubs for native methods
Compress collections of java class files into .jar archives


The most reliable way to compare two Strings for equality is by:
Using the == operator on the objects
Using the == operator on the .value() of each object
Using the &= operator on the objects
Using the .equals() or .compareTo() method of one object on the other


The part of a "try" block that is always executed is:
"enum"
"import"
"finally"
"if"


What is an example of proper capitalization for a class name?
CamelCase
CAMELcase
camELCase
camelcase


What is the correct syntax for importing java.util.Scanner?
import.java.util.scanner;
import. java.util.Scanner;
import.java.util.scanner.
import java.util.Scanner;


Finally is used to....
ensure a block of code is executed when the JVM shuts down.
ensure a block of code is executed only when try/catch completes with an exception
ensure a block of code is executed only when try/catch completes without an exception
ensure a block of code is always executed after a try/catch


How can you stop your class from being inherited by another class?
Declare the class as final.
It’s not possible.
Declare the class default constructor as private.
Declare the class as abstract.


What is the most efficient way to concatenate a large number of strings in Java?
The StringBuffer object.
The + operator.


Which of the following is a valid constructor signature?
static className()
public className()
public void className()
public static className()


If a method or variable is marked as having the "private" access level, then it can only be accessed from:
Inside the same class, or any of its superclasses
Inside the same class
Inside the same class or its parent class
Inside the same class, or a subclass


Can an abstract class be a final class?
Yes
No


What is @Override annotation used for?
It just makes your code easier to read
It makes compiler check that method is really overridden
It makes method virtual


Interfaces are useful for...
reducing heap size
creating a design contract that encapsulates implementation
implementing an abstract factory pattern
making an abstract class concrete


What is the correct way to create an instance of a class?
ClassName varName = new ClassName(arguments);
varName ClassName = new varName(arguments);
ClassName varName = new ClassName(new ClassName);
ClassName varName => new ClassName();


When you create a thread with the “new” operator – which one of the following statements is true about its state
it is blocked until another thread calls notify()
it will be “runnable” when start() method is called
it is in “runnable” state
it starts running immediately


A java class which extends another class is usually described with the word:
subclass
dynamic
overloaded
abstract


True of False? The strictfp keyword ensures that you get the same result on every platform if you perform operations in the floating point variable.
True
False


Keyword used to access members or methods of superclass?
this
Super
native
extends


Which of these is true?
An interface implements another interface and class
A class implements an interface but extends a class
A class implements and extends a class
An interrface extends a class but implements another interface


The "java" command line tool is used to:
Compress collections of java class files into .jar archives
Disassemble .class files back into readable source code
Load and execute java .class files
Compile java source files into bytecode class files


What is auto boxing?
JVM conversion between primitive types and reference types
Automatic insertion of brackets by an IDE
It doesn’t occur in Java, only in dynamically typed JVM languages like Groovy
JVM conversion of int to float values


You want subclasses in any package to have access to members of a superclass. Which is the most restrictive access that accomplishes this objective?
protected
transient
private
public


What are all the different types of access modifiers in Java
private, protected, default, public
private, protected, public
protected, default, public
private, default, public
private, public


How should you create a new class that maps keys to values, using the Java Collections Framework?
Implement both the Iterator and Array interfaces
Extend the AbstractCollection class, thereby implementing the AbstractCollection interface
Implement the Queue, List, and Array interfaces
Implement the Map interface, possibly by extending the AbstractMap class


The Object.wait() method:
Resumes from waiting if notifyAll() is invoked for the object
Causes the current thread to wait
Resumes from waiting if notify() is invoked for the object
Resumes from waiting if a specified amount of time has elapsed


How can we use the class or jar files kept on the network path, within our projects?
Including the path and class /jar file name in the Classpath
mentioning the file names in the Path
No the network files can not be used directly
mentioning the Class /Jar file names during compilation only
by directly copying and including in the same folder as of the project


The "static" keyword marks something as:
Belonging to a class, rather than a specific instance
Not being mutable after initialization
No longer able to be subclassed or overloaded
A constant variable whose value cannot be changed


What is the output of the below code ? int a = 0; int b = 0; if (a++ == 1 || b++ == 1) {} System.out.println(a + " " + b);
0 0
1 1
1 0
0 1


What will be the output of the program? public class Foo { public static void main(String[] args) { try { return; } finally { System.out.println( "Finally" ); } } }
Compilation fails.
Finally
The code runs with no output.
An exception is thrown at runtime.


What is the benefit of ConcurrentHashMap<K,V>?
Supports locking the entire table in a way that prevents all access
All operations are thread-safe and retrieval operations do not entail locking
It maintains a list through all entries to retrieve data in the order it was inserted.
Allows null to be used a key or value


When the == comparator is used on two objects, it checks to see if they:
Are instances of the same class
Are references to exactly the same object
Evaluate to the same value
Have the same value according to the .equals() method of the first object


The instanceof operator can be used to determine if an object is:
An instance of a class that implements a given interface
An instance of a subclass of a class
An instance of a class
(All of these)


When creating a user defined class for storing objects in a HashMap, which method(s) should be overridden?
The hashCode() method
The constructor method
The equal() method
Both the equals() and hashCode() methods
(You don't need override any methods)


JDBC addresses the issue of transactions.
False
True


What is the name of the method used to start a thread execution?
resume();
start();
run();
init();


Why is it important to override hashCode() when you override equals()?
It is NOT important to override hashCode() when overriding equals().
Overriding equals without hashCode breaks the contract of hashCode().
equals() will throw an exception if hashCode() is not overridden as well.


An "overloaded" method has what in common with one (or more) methods on the same class?
The same return type
The same number of parameters, regardless of type
The same name
The same number and types of parameters


Which class/classes is/are thread safe among these?
String and StringBuffer
StringBuilder


Which one of these lists contains only Java programming language keywords?
try, virtual, throw, final, volatile, transient
strictfp, constant, super, implements, do
goto, instanceof, native, finally, default, throws
class, if, void, long, int, continue
byte, break, assert, switch, include


Immutable objects are always...
polymorphic
memory efficient
serializable
thread safe


What is a LinkedHashSet?
A hash set with the performance of a linked list.
A superclass of the HashSet object.
A hash set which can easily be converted into a linked list.
A hash set which preserves the order in which objects were inserted.


Calling System.gc() when using a modern JVM :
Should be done after deleting several elements from a collection.
Is especially important when programming for mobile or memory limited devices.
Does not necessarily force garbage collection to occur, and is not idiomatic java.
Is the most straightforward and reliable way to perform memory management in Java.
Directly and immediately disposes of all orphaned objects on the heap.


In addition to CORBA, Core Java also supports network services using:
Remote Procedure Calls
IPX / SPX Protocol
Remote Object Access
Remote Method Invocation


Java provides a class for mutable sequences of characters, called:
String
MutableString
StringBuffer
CharSequence


The List interface has which superinterfaces?
Set
Collection
Both Collection and Iterable
Iterable


A method without an access modifier (i.e. public, private, protected) is...
static
protected
package-private
public
private


What is the difference between a checked and unchecked exception?
Checked exceptions must be caught while unchecked do not need to be caught
Unchecked exceptions must be caught while checked do not need to be caught
A checked exception extends Throwable and an unchecked exception does not.
An unchecked exception extends Throwable and a checked exception does not.


package test; class Test { } ---------------- package test; class SubTest extends Test{ } Is this code compile without error if the classes are in separate files?
No
Yes


A class may extend:
Only one non-final class
Only one interface
Only one inner class
Many classes through multiple inheritance


What is the output? int[] xxx = {10, 20}; List<String> list = new ArrayList<String>(10); list.add("01"); list.add("02"); System.out.println(xxx.length + ", " +list.size());
Compile error
10, 2
2, 10
2, 2
1, 2


Which option is true for StringBuffer and StringBuilder
StringBuffer are thread safe and StringBuilder are not thread safe
StringBuffer and StringBuilder are thread safe.
Neither StringBuffer nor StringBuilder are thread safe.
StringBuffer are not thread safe and StringBuilder are thread safe.


Java's automatic memory management:
Can be overriden using functions like alloc and dalloc
Uses hardcoded settings inside each Virtual Machine, which should not be altered
Can be tuned using Virtual Machine settings
Can be configured to operate statically or dynamically at compile time


After the following code fragment, what is the value in a? String s; int a; s = "Foolish boy."; a = s.indexOf("fool");
1
random value
0
-1
4


enum Example { ONE, TWO, THREE } Which statement is true?
The expressions (ONE == ONE) and ONE.equals(ONE) are both guaranteed to be true.
The Example values cannot be used in a raw java.util.HashMap; instead, the programmer must use a java.util.EnumMap.
The Example values can be used in a java.util.SortedSet, but the set will NOT be sorted because enumerated types do NOT implement java.lang.Comparable.
The expression (ONE < TWO) is guaranteed to be true and ONE.compareTo(TWO) is guaranteed to be less than one.


Java variables are passed into methods as:
Pass-by Reference
Pass-by Value
Neither


Java's String class is
Mutable, and can be subclassed
Final, with immutable instances
Final, but creates mutable instances
Immutable, but can be subclassed


Which of the following is true about overloading vs overriding methods?
Final methods can be overriden, but not overloaded
Overloading happens at compile time, while overriding happens at runtime
The argument list of overloaded methods must be of same data type (unlike overridden methods)
Overloading can arbitrarily change the access of a method, while overriding can only make it more restrictive


How do you convert int[] to a ArrayList<Integer>?
Casting
In a loop, creating new Integers.
Using the static Arrays.asList method
Using toArrayList()


A class implementing a singleton pattern has...
no public constructors and static factory method and a non-static instance variables.
public constructors instead of a static factory method and a static instance variable.
no public constructors, a public static factory method, a static instance variable.
no public constructors, a private static factory method, a static instance variable.


What is a weak reference?
A reference to an object which may have been garbage collected when the object is asked for.
A reference to an object which is about to be garbage collected.
A reference to an object that cannot be garbage collected.
A reference to an object which has been garbage collected.


Can the "main" method be overloaded
No
Yes


What type should you use for floating point monetary calculations?
float
BigDecimal
double
byte


Which statement is true?
Any statement that can throw an Error must be enclosed in a try block.
The Error class is a RuntimeException.
catch(X x) can catch subclasses of X where X is a subclass of Exception.
Any statement that can throw an Exception must be enclosed in a try block.


Which of the following is used to see the details of compilation
javac -verbose TestExample.java
javac -debug TestExample.java
None of these
javac -detail TestExample.java


What is the issue with the following code? String s = ""; for(int i = 0; i < 1000000; i++) { s += Integer.toString(i); }
It will perform very slowly because Integer.toString() is slow.
It will not compile.
There are no issues with the above code.
It will perform very slowly because strings are immutable.


Float p = new Float(3.14f); if (p > 3) { System.out.print("p is bigger than 3. "); } else { System.out.print("p is not bigger than 3. "); } finally { System.out.println("Have a nice day."); } What is the result?
p is bigger than 3. Have a nice day.
Compilation fails.
p is bigger than 3.
p is not bigger than 3. Have a nice day.


What will be printed out if you attempt to compile and run the following code? int i=9; switch (i) { default: System.out.println("default "); case 0: System.out.println("zero "); break; case 1: System.out.println("one "); case 2: System.out.println("two "); }
default
error default clause not defined
default zero
no output displayed


Which of the following statements about static inner classes is true?
A static inner class requires a static initializer.
A static inner class has no reference to an instance of the enclosing class.
A static inner class has access to the non-static members of the outer class.
A static inner class requires an instance of the enclosing class.


To create a single instance of a class, we can go with
Final class
Static class
(none of these)
Abstract class


Java source code is compiled into
Source Code
.Exe
Byte Code
.class
.obj


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 ?
Thread t = new Thread(); x.run();
X run = new X(); Thread t = new Thread(run); t.start();
Thread t = new Thread(X);
Thread t = new Thread(X); t.start();


What's the output of following error ? class A { public Number getNumber(){ return 1; } } class B extends A { public int getNumber(){ return 2; } } public class Main{ public static void main(String []args){ A a = new B(); System.out.println(a.getNumber()); } }
Compilation error
2
1
RuntimeError


What is the output of the following program? import java.lang.reflect.Method; class TestImpl { public void method() {} public static void main(String[] args) { Method method = TestImpl.class.getMethod("method", null); System.out.println(method.getName()); } }
Compilation Error
public void test.TestImpl.method()
None of the Above


All of the classes in the Java Collections Framework:
Have methods to retrieve their data as an Array
Allow elements to be added to the beginning or end of their internal List
Involve data structures backed by Arrays
Have methods allowing them to be viewed as both Maps and Lists


Does interrupt() always force all threads to terminate?
No, if the interruption is not enabled for the thread, it will not terminate
Yes, the thread gets to a predefined interruption point and stops
Yes, after interrupt() is called a thread terminates immediatelly


Given the code: Integer i= new Integer("1"); if (i.toString() == i.toString()) System.out.println("Equal"); else System.out.println("Not Equal");
None of the above
Prints "Equal"
Compiler error
Prints "Not Equal"


Anonymous inner classes have access to...
Only synchronized collections in the containing class
Final, local variables in the containing scope
Only variables passed into the constructor, and no variables in the containing class
Any local variables in the containing scope


What is the output of the below code ? int a = 0; int b = 0; if (a++ == 1 && b++ == 1); System.out.println(a + " " + b);
0 0
0 1
1 0
1 1


In your program, you need to read a zip file (myfile.zip) containing several other data files containing basic Java objects. Which of the following will allow you to construct a InputStream for the task?
new DataInputStream(new FileInputStream(“myfile.zip”));
new ZipInputStream(new ObjectInputStream(“myfile.zip”));
new ZipInputStream(new FileInputStream(“myfile.zip”));
new ObjectInputStream(new ZipInputStream( new FileInputStream((“myfile.zip”)));


LinkedBlockingQueue is useful for...
implementing a stack
implementing a producer consumer pattern
binary searches of a list of sorted objects
a synchronized linked list


java.util.Collection is:
An abstract class representing a group of objects, extended by Set and List
An interface of non-destructive methods used by Set and List classes
An interface for iterable groups of objects
An abstract interface representing a group of objects, extended by Set and List


Which one of the following statements is true about threads in Java
the notify() must be called to wake up threads that have called wait() and notifyAll() must be called to wake up threads that have called join().
the notify() method can only be called from inside a synchronized block or from a synchronized method
the notify() method can not be called if your class extends Thread class, it can only be called if your class implements the “Runnable” interface
the notify() method informs the Java Virtual Machine that it has finished executing


A "blank" final variable (defined without an initial value):
Is illegal, and will cause an error at compile time
Will raise an exception if its value is accessed or assigned at runtime
Has a Null value, and will raise an exception if initialized or assigned later
Can be initialized later, but only in a single location


which statement is True ?
The notify() method causes a thread to immediately release its locks.
To call wait(), an object must own the lock on the thread.
The notify() method is defined in class java.lang.Thread.
The notifyAll() method must be called from a synchronized context.


The keyword that ensures a field is coherently accessed by multiple threads is:
"volatile"
"switch"
"synchronized"
"native"


The TreeMap class is Java's implementation of which data structure?
Linked list
B-tree
Red-Black tree
B+ tree


I would implement a LRU cache using only JDK classes by...
A LinkedList and binary search over the last accessed timestamp
A TreeMap and iteration over values that containing a last accessed timestamp
An ArrayList and binary search over the last accessed timestamp
A Hashtable and iteration over all values that contain a last accessed timestamp.


What is the output? public static void main(String[] args) { int x=10; if(x++ > 9 && x++ == 12){ ++x; } System.out.println(x); }
13
10
12
11


Which of the following are not a valid declarations?
float f = 1.2;
float f =1;
float f = 1.2f;
float f = (float)1.2;


You need to keep a list of one million objects sorted at all times having 100 random inserts and delete per second. Reads from the list are always done in sorted order. You would:
Use a TreeMap for fast inserts and iterate over the list in order to re-sort it after each insert.
Use a PriorityQueue to keep the list ordered at all times.
Use a shell sort after each insert.
Use a HashMap to keep the list ordered at all times.


Which code fragments correctly create and initialize a static array of int elements?
static final int a = { 100,200 };
static final int[] a = new int[2]{ 100,200 };
static final int[] a; static void init() { a = new int[3]; a[0]=100; a[1]=200; }
static final int[] a; static { a=new int[2]; a[0]=100; a[1]=200; }


Which of the following is true about the Cloneable interface?
Creates an exact copy of the implementing class by calling its constructor.
It changes the behavior of the protected clone method to give a field-by-field (reference) copy of the object.
Is just a marker interface that does nothing.
It provides a clone method that must be implemented.


Livelock describes a situation in which two or more threads block each other, because:
Their actions are also responses to the actions of others, such that all are too busy to respond
Each are waiting on the other thread(s) before acting, such that no thread takes action
A call to Thread.sleep() has suspended the action on all threads in the VM
They are unable to gain access to shared resources, and cannot make any progress


You want to listen TCP connections on port 9000. How would you create the socket?
new Socket(9000);
new Socket(“localhost”, 9000);
new ServerSocket(9000);
new ServerSocket(“localhost”, 9000);


Which two are valid constructors for Thread? 1. Thread(Runnable r, String name) 2. Thread() 3. Thread(int priority) 4. Thread(Runnable r, ThreadGroup g) 5. Thread(Runnable r, int priority)
1 and 3
1 and 4
2 and 5
2 and 4
1 and 2


The TreeMap and LinkedHashMap classes:
Enable iteration of a map's entries based on natural ordering of keys only.
Enable iteration of a map's entries in a deterministic order.
Enable iteration of a map's entries based on the insertion order of elements only.
Enable iteration of a map's entries based either natural ordering of keys OR natural ordering of values - depending on the arguments sent to the constructor.


What will be the output of this code? class Main { static abstract class Base { protected Base() { init(); } abstract void init(); } static class Child extends Base { private final int value; public Child() { value = 5; } @Override public void init() { System.out.println("value = " + value); } } public static void main(String[] args) { Child c = new Child(); } }
Runtime exception
Compilation error
value = 0
value = 5


public class Test{ public static void main(String [] arg){ int x=10; if(x++ > 10 && x++ == 12){ ++x; } System.out.println(x); } } What is the Output of this code?
10
13
12
11


A Guarded Block is a concurrency idiom in which:
A block of code will only ever be executed in synchronized mode
All statements in a block of code are guaranteed to be executed completely, or not at all
A condition is polled before the execution of a code block can proceed
A block of code is protected by an intrinsic lock obtained from a specific Object or Class