Elance JAVA Test Answers 2015
·
A function that defines the steps necessary to
instantiate one object of that class is called:
an instantiator.
a destructor.
a constructor.
What does the synchronized keyword on a method
do?
Uses the object's intrinsic lock to prevent two threads
from accessing the method simultaneously.
Creates a new semaphore to prevent two threads from
accessing the method simultaneously.
Prevents objects outside the current package from
accessing the method.
Ensures that each call to a synchronized method is
run in a separate thread.
Given the code: Integer i= new
Integer("1"); if (i.toString() == i.toString())
System.out.println("Equal"); else System.out.println("Not
Equal");
Prints "Equal"
None of the above
Compiler error
Prints "Not Equal"
Consider the following code: int
i=aReader.read(); What is the true of the type of variable aReader?
It has to be a FileReader
It can either be a FileReader or a BufferReader.
It can neither be a FileReader or a BufferReader.
It has to be a BufferReader.
If "A" is a class, then what does
the statement "A a1;" do?
The statement does not do anything.
An object 'a1' of class 'A' is created.
The object reference variable 'a1' should be in
title case.
The syntax is incorrect.
The object reference variable 'a1' is declared.
What is displayed when the following code is
compiled and executed? String s1 = new String("Test"); String s2 =
new String("Test"); if (s1==s2) System.out.println("Same");
if (s1.equals(s2)) System.out.println("Equals");
Same
Equals
Same Equals
The code compiles, but nothing is displayed upon
execution.
Do we need to import the java.lang package at
anytime?
No
Yes
The pattern described below is known as:
public class Foo{ private static Foo instance; private Foo(){ } private static
getInstance(){ if (instance == null){ instance = new Foo(); } return instance;
}
the Singleton pattern
the Observer Pattern
the Flyweight pattern
the Factory pattern
Suppose ArrayList x contains two strings
[Beijing, Singapore]. Which of the following methods will cause the list to
become [Beijing, Chicago, Singapore]?
x.add(1, "Chicago")
x.add(0, "Chicago")
x.add(2, "Chicago")
x.add("Chicago")
Which statement is wrong?
ArrayList<Integer> myList = new
ArrayList<Integer>();
ArrayList<Double> myList = new
ArrayList<Double>();
ArrayList<String> myList = new
ArrayList<Integer>();
ArrayList<String> myList = new
ArrayList<String>();
ArrayList<String> myList = new
ArrayList<String>(10);
Under the strictest definition, an interface
may contain only:
constructors
fields
additional pylons
abstract methods
which of the following is a correct statement:
a class can inherit multiple abstract superclass
a class can implement multiple interface
a class can inherit multiple superclass
What is the syntax for creating a class
derived from the class named MyClass?
public class MyDerived : MyClass
class MyDerived implements MyClass
class MyDerived extends MyClass
When you run a Java program, the system is
running the Java Runtime Engine (JRE) as an executable which then:
process the java code through the interpreter which
is pointed to by the CLASSPATH statement.
processes the java code through the Java Virtual
Machine (JVM).
none of these
processes the java code through the native OS
interpreter.
Consider public class MyClass{ public
MyClass(){/*code*/} // more code... } To instantiate MyClass, you would write?
MyClass mc = new MyClass();
MyClass mc = MyClass();
MyClass mc = MyClass;
It can't be done. The constructor of MyClass should
be defined as public void MyClass(){/*code*/}
MyClass mc = new MyClass;
_____ jumps out of an entire loop, whereas
_____ jumps to the next iteration.
stop; jump
stop; continue
break; continue
break; jump
Consider the following code snippet String
river = new String(“Columbia”); System.out.println(river.length()); What is
printed?
7
Columbia
8
6
river
The correct operator for 'conditional or' is:
&
||
|
&&
Do you need to explicitly define a constructor
for every class?
Yes
No
public class Dog extends Animal{ ... } is an
example of...
Encapsulation
Abstraction
Type casting
Inheritance
Which keywords would you use to handle
exceptions in Java?
try, catch, end
throw, catch, do
throw, take, finally
try, catch, finally
throw, catch, end
Class definitions in Java can have which of
the following access levels?
private
protected
public
all of these
All Java files must have a .java extension and
are compiled with the:
system runtime compiler
javac compiler
gcc compiler
An applet can do which of the following?
Self initialize
Stop running
Start running
All of these
Which of the following is the correct
signature for a main method that can be used as an entry point by the Java
runtime?
public void main(String[] args)
public static int main(String[] args)
public static void main(Collection<String> c)
public static void main(String[] args)
The varargs method: public void foo(String...
strings) may be called with:
foo("bar1", "bar2",
"bar3");
foo("bar1", "bar2");
All of these.
foo("bar1");
The process of changing a datatype of a value
is called:
typecasting
hardcasting
datatyping
What is the proper syntax for a Java class's
main method?
private static void main(String[] args)
public static void main(String[] args)
private void main (String[] args)
public static main(String[] args)
public void static main(String[] args)
What are the core JMS-related objects required
for each JMS-enabled application?
Within a session, the appropriate sender or
publisher or receiver or subscriber objects.
All of these
A connection object provided by the JMS server (the
message broker)
Within a connection, one or more sessions, which
provide a contest for message sending and receiving
A JavaBean is a special Java class:
which must be serializable so that the state can be
stored.
all of these
which must follow standard naming conventions for
attributes such as getXxxx.
which must have a public, no-argument constructor.
Which of these keywords is used to define
packages in Java?
pack
pkg
Package
Pkg
package
Which of the following is correct way of
importing an entire package ‘pkg’?
import pkg
Import pkg.*
import pkg.*
Import pkg
How do you declare a destructor in Java?
myClass::~myClass();
You don't need a destructor
@destructor myClass(){ }
@Override System.gc(){ }
You can use the 'static' keyword for which of
the following?
Classes
All of these
Methods
Variables
As a general syntax rule, Java is case
sensitive on:
all platforms.
only Microsoft Windows platforms.
only on UNIX based platforms.
Can an interface have member variables?
No, never
Yes, as long as they are public, static and final
Will a program run if the main() is not
static?
No
Yes
What keyword is used to add external package
members to the current Java file?
import
using
get
add
uses
Which of the following JNDI properties provide
security information?
java.naming.security.principal
All of these
java.naming.security.credential
java.naming.security.authentication
What company developed java?
IBM
Facebook
Sun Microsystems (Oracle)
Google
Microsoft
Which of the following is correct for the
"main" method of a class?
@Main public void main(int argc, String[] argv) {}
public static void main(String [] args) { }
public void main(int argc, String [] argv) {}
public final void main(String arg0, String
arg1="default") {}
What effect does declaring a method as final
have?
The method can only accept final parameters.
The return value of the method will be final.
The parameters passed to the method cannot be
modified.
The method cannot be overridden in subclasses.
How do you prevent a class from being extended
by a subclass?
Declare all its members as private.
Declare the class as abstract.
Declare all member variables and methods as
protected.
Declare the class as final.
You read the following statement in a valid
Java program: submarine.dive(depth); What must be true?
"dive" must be a method.
"dive" must be the name of an instance
field.
"submarine" must be a method.
"submarine" must be the name of a class.
"depth" must be an int.
What's wrong with the following method: public
static int getSize(){ int temp = super.getSize(); if(temp==0) temp=this.size;
return temp; }
static methods cannot refer to "this" or "super"
static methods cannot return type "int"
There is nothing wrong with this method.
Are primitive data types passed by reference
or passed by value?
Passed by reference
Passed by value
________ is when a subclass implements a
method that is already provided by a superclass.
Method overriding
Method overloading
Method overdriving
Object orientation overdev
If I write return at the end of the try block,
will the finally block still execute?
No
Yes
What is a token?
A token is a group of digits
A token is a group of characters that means
something in a particular context.
A token is any character that may be used as
punctuation
A token is a type of expression
What will be the output of below code String
a="abc"; String b="abc"; String c=new
String("abc"); if(a==c && a.equals(b)){
System.out.println("They are equal"); } else
System.out.println("They are not equal");
They are not equal
They are equal
A deadlock error occurs when a Java program
has a for loop or while loop that can never satisfy
its condition, causing the loop to run forever and the program to wait
indefinitely.
has a circular try-catch block, in which the catch
results in the catch block being reached again repeatedly, causing the program
to run indefinitely.
has a circular dependency on 2 or more synchronized
objects, causing one of the objects to wait indefinitely.
The StringBuffer and StringBuilder classes in
Java are optimized for
retrieval of all or part of a string but not
altering the string.
creating strings which change considerably.
creating strings which only change once.
Java allows you to specify two types of
variables: primitive, which store a single value, and
reference, where the data is accessed indirectly.
neither of these
wide, which reference a double byte variable.
The "synchronized" keyword does the
following
Prevents concurrency within methods or statements
Aligns samples within the JVM for accuracy when
profiling
Prohibits code from being executed during garbage
collection
Provides a convenient shortcut for creating threads
Ensures that each call finishes at the same time
Which Map implementation is safe for
modification in a multi-threaded program?
java.util.concurrent.ConcurrentHashMap
java.util.TreeMap
java.util.LinkedHashMap
java.util.WeakHashMap
Can you mark an interface as final?
Yes
No
A method is considered to be overloaded when:
You cannot overload a method
the method throws an exception
they have multiple call signatures
they have different return types
Can a class be both abstract and final?
Yes
No
Can you declare an abstract class with no
abstract methods?
No
Yes
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
Can we override a static method?
Yes
No
Can static and abstract keywords be used
together?
No
Yes
Which one of these primitive types is
unsigned?
long
double
int
char
float
Java programs must have at least one method
called main() _____.
Both of these
In order to compile
In order to execute
TreeMap class is used to implement which
collection interface?
List
SortedMap
SortedSet
Set
What is transient variable?
It is the default variable in the class.
A variable which is not static.
A variable which is not serialized.
A variable which is serialized.
Java interfaces can extend...
nothing: extension is not valid for interfaces.
multiple interfaces.
final classes.
one other interface.
Which of the following is *not* a method in
java.lang.String?
String valueOf(char[] data)
boolean isNull()
String toString()
int compareTo(String anotherString)
If you override method "equals()",
what other function you must override for the class to work properly?
public int hashCode()
public int hash()
public static int hash()
public static int hashCode()
String objects in Java are immutable which
means:
that, if constant, they cannot be changed once they
are created.
that they can be changed multiple times without
altering the reference.
that they can be changed one time without changing
the reference.
What is the keyword to forbid the
serialization of an instance field?
transient
synchronized
break
serializable
volatile
Will a program compile if the main method is
defined private?
No, it does not compile
Yes, but will not run
Java's Reflection feature allows you to do
things including (but not limited to) :
Optimize recursion at runtime by extending the
reflection class.
Dynamically change the Java Heap Size.
Perform pseudo-pointer manipulations in Java.
Obtain the names of a class' members and display
them at runtime.
What is the difference between Vector and
ArrayList?
ArrayList is synchronized whereas Vector is not
Both are identical
Vector is synchronized whereas ArrayList is not
Which is a valid keyword in Java?
Float
interface
unsigned
string
The @Override annotation
All of these answers are correct
Is not required to implement an interface method.
Is not required to override an inherited method in
a parent class.
Will warn you on compilation if your annotated
method signature doesn't match a method in a parent class or interface.
Clearly documents the intention to override a
method in a parent class or implement a method declared in an interface.
The foreach loop in Java is constructed as:
for (Object o in collection)
foreach (Object o : collection)
foreach (collection as Object o)
there is no foreach loop in Java
for (Object o : collection)
Is it possible to create zero length arrays?
Yes, but only for primitive datatypes
Yes, you can create arrays of any type with length
zero
No, you cannot create zero length arrays, but the
main method may be passed an array of String references that is of length zero
if a program is started without any arguments
Yes, but only for arrays of object references
No, arrays of length zero do not exist in Java
Which of these is the wildcard symbol for use
in generic type specification?
!
%
&
?
If you set one object variable equal to
another object variable:
you end up with two copies of the data and two
references to the variable.
you end up with one copy of the data and two
references to the data.
you end up with one copy of the data and one
reference to the data.
SWING Toolkit contains
component set (subclasses of JComponent),support
classes,interfaces
support classes,interfaces
interfaces,component set (subclasses of JComponent)
component set (subclasses of JComponent)
In Math and other java.lang Classes, generally
all methods are declared _.
final
static
package private
private
abstract
How do we compare enum types in java
Equals Method
Both
Arithmetic comparator "=="
what are the parts of JNDI architecture
Java API
JNDI API and JNDI SPI
JNDI API
JNDI SPI
Which of the following is true for interface
variables.
They cannot exist and the compiler will throw a
'field name is ambiguous' error if you attempt to make them.
They may exist, and they can be transient and
volatile.
They may exist, and they can be transient but not
volatile.
They may exist, but they must be public, static and
final.
They may exist, and they can be volatile but not
transient.
Which of the following is not a legal
identifier?
$cash
_class
m1g
31days
A call to System.gc() does what?
Grants control of the System object to the
currently executing thread.
Forces the JVM to run garbage collection to reclaim
memory.
Suggests that the JVM run garbage collection to
reclaim memory.
find the correct output: StringBuffer fb= new
StringBuffer("one two one"); int i, j ; i=
fb.indexOf("one"); System.out.println(i); j=
fb.LastIndexOf("one"); System.out.println(j);
1,8
0,3
1,3
0, 8
Is "main" a keyword in Java?
Yes
No
Which method is used to sort a Collection by
natural order of its elements?
Sort.sort
Collections.sort
Collection.sort
CollectionsUtils.sortCollection
Can a non-generic class have a generic
constructor?
Yes
No
What does a synchronized method use as a mutex
in Java?
The owning object's (this's) mutex.
The method's mutex.
A globally declared mutex.
The Java Virtual Machine manages its own:
memory and allocates it as necessary.
both of these
namespace and allocates more if necessary.
none of these
Which exception could be thrown if x is a
String variable? while (x.equals("apple")) {
java.lang.ClassNotFoundException
java.lang.NoSuchMethodException
None of these exceptions can be thrown.
java.lang.NullPointerException
Which of the following IS NOT a property of
the equals() method?
reflexive
transitive
symmetric
atomic
Are static fields of a class included in
serialization?
No
Yes
Can a HashMap contain a null key?
No
Yes
What is an abstract class?
A class with an undefined constructor
A class that is defined by another class
A class of methods that must be implemented
A class that does not define all of its methods
Non-static attributes can be accessed without
an instance of the class.
True
False
Only if they are public
Only if they are private
What is the default scope of a method?
protected
package-private
public
private
static
What is the assignment of 'animal' an example
of in the following code? public abstract class Animal{...} public class Dog
extends Animal{...} Animal animal = new Dog();
Polymorphism
Inheritance
Encapsulation
Abstraction
Typecasting
Which of these keywords is used to manually
clean up memory in java?
finalizeGarbageCollection
finalize
final
finally
If you need to determine exactly which class
your object is:
use the myClass property.
use the instanceOf operator.
use the getClass() method.
Which of the following *classes* include the
getSession method used to retrieve an object that implements the HttpSession
interface?
HttpServletRequest
HttpServletResponse
SessionConfig
Session Context
When is an object's finalize method called?
Whenever the JVM's garbage collection algorithm
decides to call it.
When no references to the object exist in the
application.
When System.gc() is called.
When the object needs to release any resources it
holds.
What is one of the benefits of Generics in
Java?
Enforcement of better Casting at Complie time
Easy handling of ClassCastException at runtime
Improved Runtime type checking
Elimination of Casts when getting objects from
Collections
Which of the following is false regarding a
class of a JavaBeans component?
it is serializable.
it is a public class
it has a public constructor with no arguments
it is transient
package test; public class Test { } --------
package test.subtest; public class SubTest extends Test{} Is this code compiles
without error?
No
Yes
Which method is used to force one thread to
wait for another thread to finish?
sleep(long milliseconds)
stop()
yield()
join()
which of the following can cause serious
system failures??
sleep()
stop()
resume()
suspend()
Which of the following APIs is used to create
secure socket connections and manage digital certificates?
JSSE
Servlet
JTAPI
JNDI
Which of the following can be abstract?
All of these
Private Methods
Static Methods
Constructors
None of these
Which of these statements is correct?
new and delete are keywords in the Java language
for, while and next are keywords in the Java
language
return, goto and default are keywords in the Java
language
try, catch and copy are keywords in the Java
language
Does Java provide any construct to find out
the size of an object?
Yes, the sizeof operator
No
The keyword 'volatile' on a field is used in
Java to:
Make the compiler aware that a variable will change
frequently at runtime and allow the compiler to optimize for this.
Guarantee that the field's current value is read,
not a thread-cached value.
Allow access to memory mapped devices (memory
mapped I/O).
Which of the following variable declarations
is illegal in Java?
float myVar = 5.7f;
List<int> myVar;
List<HashMap<String,Integer>> myVar;
Double[] myVar = {1.0,2.0,2.5,2.7};
What is the difference between static inner
class and a non static inner class?
A static inner class can only have static methods,
an inner class may have non static methods.
A static inner class has no difference from a non
static inner class.
An inner class has no reference to its parent
class, a static inner class does.
A static inner class has no reference to its parent
class, a non static inner class does.
Which JVM parameter is used to set the maximum
heap memory size?
XX:PermGemSize
Xxx
Xms
Xmx
Which java class provides variables local to
each thread?
Runnable
LocalThread
ThreadLocal
Thread
String x = "abc"; In this code, abc
is:
an Immutable String Object
a Mutable String Object
an Immutable String Literal
a Mutable String Literal
Which of the following is true about this Java
snippet: String a = "hello"; String b = "hello"; boolean x
= (a == b);
x is never true because you are comparing two
different Objects.
x is true because the String values are different.
x can be true because of Java String interning.
An exception is thrown because you cannot compare
Strings this way.
How many objects are created: String
s1="String"; String s2="String"; String
s3="String";
One
Two
Three
If I write System.exit (0); at the end of the
try block, will the finally block still execute?
Yes
No
An Enum implicitly implements which of the
following interfaces?
Observer and Listener
Set and Comparable
Cloneable and Serializable
Comparable and Serializable
Iterable and Set
A java.util.ConcurrentModificationException
can be thrown in a mono-threaded application.
True
False
boolean b = 1 > 0 ? 1 < 0 : false; What
is the value of b?
The code will not compile.
true
false
What are the minimum and maximum values of a
byte?
-128 and 127
-8 and 7
This depends on the Java Virtual Machine
implementation.
-255 and 256
-127 and 128
Which of the following statements are true?
(1 >>> 1) == Integer.MAX_VALUE
(-1 >> 1) == Integer.MAX_VALUE
(-1 >>> 1) == Integer.MAX_VALUE
(1 << 31) == Integer.MAX_VALUE
(1 <<< 31) == Integer.MAX_VALUE
Which of the following statements is true?
(-1 >>> 1) == Integer.MAX_VALUE
(1 << 31) == Integer.MAX_VALUE
(-1 >> 1) == Integer.MAX_VALUE
(1 >>> 1) == Integer.MAX_VALUE
What is the result when you compile and run
the following code? public class Test { public void method() { for(int i = 0; i
< 3; i++) { System.out.print(i); } System.out.print(i); } }
0123
None of these
Compilation error
0122
Java is a pure object oriented language. true
or false?
false
true
Which one of the following statements is
false?
An abstract class may implement an interface
without defining any of its methods.
An abstract class may have a no-argument
constructor.
An abstract class cannot implement an interface.
You can have member variables in an abstract class.
If x is a byte and y is a double, what is an
acceptable type for variable z in this expression? z = (short) x/y * 2;
Short
Int
Double
Byte
Long
What's the worst-case complexity of the
function Arrays.sort(int[])?
O(n)
O(n^2)
O(2^n)
O(n*log(n))
During execution of code inside a
"synchronized" statement, threads other than the executing one are
prevented from:
Acquiring any locks currently held by the executing
thread
Making progress until the executing thread exits the
block
Acquiring the built-in lock associated with the
object referenced by the synchronized statement
Accessing members of the object referenced by the
synchronized statement
How many bytes are in a long in Java?
32
16
8
4
2
A nested class declared inside a block (a
local class) can access other variables defined in its immediately enclosing
scope, but only when they are:
public
primitives
final
initialized
declared before the class
Which of the following is true about
overloading vs overriding methods?
Overloaded methods must be the same data type
Final methods can be overriden, but not overloaded
Overloading arbitrarily changes method access
Overloading happens at compile time
In Java, "const" is:
not a java keyword
a regular java keyword
a reserved but unused keyword
Which of the following lines will not throw a
compile time error?
int a2[5];
All throw compile time errors.
int []a1[] = new int[3][3];
int a2[4] = {3,4,5,6};
What is the difference between an inner class
and a nested class?
A nested class is any class that is defined within
another class. An inner class is a static nested class.
An inner class is any class that is defined within
another class. A nested class is an abstract inner class.
A nested class is any class that is defined within
another class. An inner class is a non-static nested class.
There is no difference; they are synonymous.
A subclass's constructor will always
implicitly call its superclass's default, no-argument constructor except when:
The subclass constructor in question makes an
explicit call to another of its superclass's constructors.
The subclass defines additional constructors to its
default, no-argument constructor.
The superclass is abstract.
The superclass defines additional constructors to
its default, no-argument constructor.
Can you overload a static method signature?
No
Yes
By which method does Java pass data?
Both pass by reference and pass by value.
Pass by reference only.
Pass by value only.
Can a constructor be final?
Yes
No
What will be the output of following Java
code: int someVariable = 10_000; int someAnotherVar = 10000; if(someVariable ==
10000){ System.out.println("equal"); } else{
System.out.println("not equal"); }
Runs successfully and prints "not equal"
Compile time error
Run time error
Runs successfully and prints "equal"
When using swing, which of the following is
NOT a method on a JCheckBox object?
checkb.addListener(Listener);
checkb.addItemListener(item-listener);
checkb.isSelected();
checkb.setSelected(state);
Of the following, which is not a java.lang
Class?
StringBuffer
Math
StringBuilder
Void
Arrays
True or false? StringBuilder is Thread-safe.
True
False
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 1
1 1
1 0
0 0
such construct in Java: class Foo { { // some
code } }
is another way to define the constructor
is an instance initializer, additional to
constructor and called after it
is a class initializer, for a static fields
initialization
is not proper, doesn't exist in Java
is an instance initializer, additional to
constructor and called before it
Is it possible to start a thread twice?
No
Yes
byte a = 64; byte b = (byte) (a << 2);
What is the value of b?
64
256
0
128
-1
Add this annotation to your annotation
declaration in order to ensure it's available for reflection.
@Runtime
@Target("RUNTIME")
@Retention(RetentionPolicy.REFLECTION)
@Reflectable
@Retention(RetentionPolicy.RUNTIME)
The default constructor of an enum type is
implicitly:
private
protected
public
public @interface A { String value(); } How
would you change the "value" element declaration to give it an empty
String as its default?
String value() default "";
String value("");
String value() = "";
String value() {return "";};
String value(default="");
Which of these statements is TRUE for enums:
All of the above.
Enum can extend another enum.
Enum can implement an interface.
Enum can extend a class.
Subscribe to:
Posts (Atom)