Do you know that? 77% of freelancers are OPTIMISTIC about their business prospects next

Contact Email:

<< All Upwork (oDesk) and Elance Tests << Elance test answers << IT & Programming category

Test answers for Java 2020

(144, CL) Last updated: January 23
Elance • IT & Programming
Questions and answers are regularly updated. Answered and not answered tests questions.

This helps getting job: Hundreds of (cover letter examples , interview questions , profile samples ) • Earn on Upwork (oDesk)
Job assistance: jobs popularityfreelance rates

Popular test answers: HTML, .Net, CSS, English, SEO, Photoshop, iOS, Java, Android, Ruby, Python, JavaScript

See all 6 tests answers updated

Find Upwork (oDesk) and Elance test answers on this website:

Collapse | Expand

144 Answered Test Questions:

1. A function that defines the steps necessary to instantiate one object of that class is called:


• a constructor.

• an instantiator.

• a destructor.

2. TreeMap class is used to implement which collection interface?


• SortedMap

• SortedSet

• Set

• List

3. What is the keyword to forbid the serialization of an instance field?


• synchronized

• serializable

• transient

• break

• volatile

4. Which of the following is not a legal identifier?


• 31days

• _class

• m1g

• $cash

5. How do we compare enum types in java


• Arithmetic comparator "=="

• Both

• Equals Method

6. Which of the following is true for interface variables.


• They may exist, but they must be public, static and final.

• 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 but not volatile.

• They may exist, and they can be volatile but not transient.

• They may exist, and they can be transient and volatile.

7. If "A" is a class, then what does the statement "A a1;" do?


• The statement does not do anything.

• The object reference variable 'a1' should be in title case.

• The syntax is incorrect.

• An object 'a1' of class 'A' is created.

• The object reference variable 'a1' is declared.

8. Java interfaces can extend...


• nothing: extension is not valid for interfaces.

• final classes.

• multiple interfaces.

• one other interface.

9. Which one of these primitive types is unsigned?


• double

• char

• long

• float

• int

10. Which of the following is *not* a method in java.lang.String?


• boolean isNull()

• String toString()

• String valueOf(char[] data)

• int compareTo(String anotherString)

11. A deadlock error occurs when a Java program


• has a circular dependency on 2 or more synchronized objects, causing one of the objects to wait indefinitely.

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

12. You read the following statement in a valid Java program: submarine.dive(depth); What must be true?


• "submarine" must be a method.

• "dive" must be the name of an instance field.

• "dive" must be a method.

• "submarine" must be the name of a class.

• "depth" must be an int.

13. If I write return at the end of the try block, will the finally block still execute?


• Yes

• No

14. How do you prevent a class from being extended by a subclass?


• Declare all its members as private.

• Declare the class as abstract.

• Declare the class as final.

• Declare all member variables and methods as protected.

15. Do we need to import the java.lang package at anytime?


• Yes

• No

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

17. Suppose ArrayList x contains two strings [Beijing, Singapore]. Which of the following methods will cause the list to become [Beijing, Chicago, Singapore]?


• x.add(0, "Chicago")

• x.add(2, "Chicago")

• x.add(1, "Chicago")

• x.add("Chicago")

18. 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 Factory pattern

• the Singleton pattern

• the Observer Pattern

• the Flyweight pattern

19. Which statement is wrong?


• ArrayList<String> myList = new ArrayList<String>();

• ArrayList<String> myList = new ArrayList<String>(10);

• ArrayList<Integer> myList = new ArrayList<Integer>();

• ArrayList<Double> myList = new ArrayList<Double>();

• ArrayList<String> myList = new ArrayList<Integer>();

20. What's wrong with the following method:  public static int getSize(){     int temp = super.getSize();     if(temp==0)         temp=this.size;     return temp; }


• There is nothing wrong with this method.

• static methods cannot return type "int"

• static methods cannot refer to "this" or "super"

21. Under the strictest definition, an interface may contain only:


• additional pylons

• fields

• abstract methods

• constructors

22. Are primitive data types passed by reference  or passed by value?


• Passed by value

• Passed by reference

23. What effect does declaring a method as final have?


• The parameters passed to the method cannot be modified.

• The method cannot be overridden in subclasses.

• The return value of the method will be final.

• The method can only accept final parameters.

24. Can an interface have member variables?


• No, never

• Yes, as long as they are public, static and final

25. Which of the following is correct way of importing an entire package ???pkg????


• Import pkg.*

• Import pkg

• import pkg.*

• import pkg

26. Will a program run if the main() is not static?


• No

• Yes

27. Which of the following JNDI properties provide security information?



• All of these



28. A JavaBean is a special Java class:


• which must have a public, no-argument constructor.

• which must follow standard naming conventions for attributes such as getXxxx.

• all of these

• which must be serializable so that the state can be stored.

29. Which of these keywords is used to define packages in Java?


• Package

• package

• pack

• pkg

• Pkg

30. What is the syntax for creating a class derived from the class named MyClass?


• class MyDerived extends MyClass

• class MyDerived implements MyClass

• public class MyDerived : MyClass

31. How do you declare a destructor in Java?


• myClass::~myClass();

• You don't need a destructor

• @Override System.gc(){ }

• @destructor myClass(){ }

32. Consider the following code snippet    String river = new String(???Columbia???); System.out.println(river.length());    What is printed?


• river

• 6

• 7

• Columbia

• 8

33. Do you need to explicitly define a constructor for every class?


• Yes

• No

34. What is the proper syntax for a Java class's main method?


• public static void main(String[] args)

• private static void main(String[] args)

• private void main (String[] args)

• public void static main(String[] args)

• public static main(String[] args)

35. When you run a Java program, the system is running the Java Runtime Engine (JRE) as an executable which then:


• processes the java code through the Java Virtual Machine (JVM).

• process the java code through the interpreter which is pointed to by the CLASSPATH statement.

• processes the java code through the native OS interpreter.

• none of these

36. int x; 		for( x = 0; x<3; x++ ); 		{ 			System.out.print(x); 		}  What is the output?


• 0

• 012

• 12

• 3

37. _____ jumps out of an entire loop, whereas _____ jumps to the next iteration.


• Break; continue

• Stop; jump

• Break; jump

• Stop; continue

38. What are the core JMS-related objects required for each JMS-enabled application?


• Within a connection, one or more sessions, which provide a contest for message sending and receiving

• A connection object provided by the JMS server (the message broker)

• Within a session, the appropriate sender or publisher or receiver or subscriber objects.

• All of these

39. Consider    public class MyClass{  public MyClass(){/*code*/}  // more code...  }    To instantiate MyClass, you would write?


• MyClass mc = new MyClass;

• MyClass mc = new MyClass();

• MyClass mc = MyClass;

• It can't be done. The constructor of MyClass should be defined as public void MyClass(){/*code*/}

• MyClass mc = MyClass();

40. The correct operator for 'conditional or' is:


• ||

• &&

• &

• |

41. The process of changing a datatype of a value is called:


• datatyping

• typecasting

• hardcasting

42. Which keywords would you use to handle exceptions in Java?


• try, catch, finally

• throw, catch, end

• throw, catch, do

• try, catch, end

• throw, take, finally

43. The varargs method:  public void foo(String... strings)   may be called with:


• foo("bar1");

• All of these.

• foo("bar1", "bar2", "bar3");

• foo("bar1", "bar2");

44. public class Dog extends Animal{ ... } is an example of...


• Encapsulation

• Type casting

• Abstraction

• Inheritance

45. Class definitions in Java can have which of the following access levels?


• protected

• private

• public

• all of these

46. What keyword is used to add external package members to the current Java file?


• Time's Up!

• get

• uses

• using

• import

• add

47. All Java files must have a .java extension and are compiled with the:


• javac compiler

• gcc compiler

• system runtime compiler

48. An applet can do which of the following?


• Stop running

• Self initialize

• All of these

• Start running

49. 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 void main(Collection<String> c)

• public static int main(String[] args)

• public static void main(String[] args)

50. As a general syntax rule, Java is case sensitive on:


• all platforms.

• only Microsoft Windows platforms.

• only on UNIX based platforms.

51. You can use the 'static' keyword for which of the following?


• Variables

• All of these

• Methods

• Classes

52. Which of the following is correct for the "main" method of a class?


• public void main(int argc, String [] argv) {}

• @Main public void main(int argc, String[] argv) {}

• public final void main(String arg0, String arg1="default") {}

• public static void main(String [] args) { }

53. What company developed java?


• Sun Microsystems (Oracle)


• Facebook

• Google

• Microsoft

54. Can we override a static method?


• Yes

• No

55. ________ is when a subclass implements a method that is already provided by a superclass.


• Object orientation overdev

• Method overloading

• Method overdriving

• Method overriding

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

• Same Equals

• The code compiles, but nothing is displayed upon execution.

• Equals

57. Can you declare an abstract class with no abstract methods?


• No

• Yes

58. Can you mark an interface as final?


• No

• Yes

59. Java allows you to specify two types of variables: primitive, which store a single value, and


• wide, which reference a double byte variable.

• neither of these

• reference, where the data is accessed indirectly.

60. Can static and abstract keywords be used together?


• Yes

• No

61. 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 only change once.

• creating strings which change considerably.

62. What is a token?


• A token is any character that may be used as punctuation

• A token is a group of digits

• A token is a type of expression

• A token is a group of characters that means something in a particular context.

63. A method is considered to be overloaded when:


• You cannot overload a method

• they have different return types

• they have multiple call signatures

• the method throws an exception

64. Which Map implementation is safe for modification in a multi-threaded program?


• java.util.TreeMap

• java.util.LinkedHashMap

• java.util.concurrent.ConcurrentHashMap

• java.util.WeakHashMap

65. The "synchronized" keyword does the following


• Prevents concurrency within methods or statements

• Prohibits code from being executed during garbage collection

• Aligns samples within the JVM for accuracy when profiling

• Ensures that each call finishes at the same time

• Provides a convenient shortcut for creating threads

66. Can a class be both abstract and final?


• Yes

• No

67. What is the difference between Vector and ArrayList?


• ArrayList is synchronized whereas Vector is not

• Vector is synchronized whereas ArrayList is not

• Both are identical

68. String objects in Java are immutable which means:


• that they can be changed one time without changing the reference.

• that, if constant, they cannot be changed once they are created.

• that they can be changed multiple times without altering the reference.

69. The @Override annotation


• Is not required to implement an interface method.

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

• All of these answers are correct

• Is not required to override an inherited method in a parent class.

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

• Obtain the names of a class' members and display them at runtime.

• Perform pseudo-pointer manipulations in Java.

71. If you override method "equals()", what other function you must override for the class to work properly?


• public int hash()

• public static int hashCode()

• public int hashCode()

• public static int hash()

72. The foreach loop in Java is constructed as:


• foreach (collection as Object o)

• there is no foreach loop in Java

• for (Object o in collection)

• foreach (Object o : collection)

• for (Object o : collection)

73. Java programs must have at least one method called main() _____.


• Both of these

• In order to execute

• In order to compile

74. Which exception could be thrown if x is a String variable?  while (x.equals("apple")) {


• None of these exceptions can be thrown.

• java.lang.ClassNotFoundException

• java.lang.NullPointerException

• java.lang.NoSuchMethodException

75. What is transient variable?


• It is the default variable in the class.

• A variable which is not static.

• A variable which is serialized.

• A variable which is not serialized.

76. Is it possible to create zero length arrays?


• Yes, but only for arrays of object references

• 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, you can create arrays of any type with length zero

• No, arrays of length zero do not exist in Java

• Yes, but only for primitive datatypes

77. Non-static attributes can be accessed without an instance of the class.


• Only if they are private

• True

• Only if they are public

• False

78. Will a program compile if the main method is defined private?


• Yes, but will not run

• No, it does not compile

79. The Java Virtual Machine manages its own:


• memory and allocates it as necessary.

• namespace and allocates more if necessary.

• none of these

• both of these

80. Which is a valid keyword in Java?


• unsigned

• string

• Float

• interface

81. Which of these is the wildcard symbol for use in generic type specification?


• &

• !

• %

• ?

82. A call to System.gc() does what?


• Forces the JVM to run garbage collection to reclaim memory.

• Grants control of the System object to the currently executing thread.

• Suggests that the JVM run garbage collection to reclaim memory.

83. Which of the following IS NOT a property of the equals() method?


• reflexive

• atomic

• symmetric

• transitive

84. Which answer best describes the following two code examples:  A) if( x.equals( "hello" ) ) { } B) if( "hello".equals(x) ) { }


• "B" is better for performance reasons.

• "A" is better for performance reasons.

• "B" is better because "A" won't compile.

• "B" is better because "A" could throw an Exception

85. What does a synchronized method use as a mutex in Java?


• The owning object's (this's) mutex.

• A globally declared mutex.

• The method's mutex.

86. Are static fields of a class included in serialization?


• Yes

• No

87. 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 one reference to the data.

• you end up with one copy of the data and two references to the data.

88. What is an abstract class?


• A class that does not define all of its methods

• A class of methods that must be implemented

• A class that is defined by another class

• A class with an undefined constructor

89. Is "main" a keyword in Java?


• No

• Yes

90. Can a non-generic class have a generic constructor?


• Yes

• No

91. What does the synchronized keyword on a method do?


• Creates a new semaphore to prevent two threads from accessing the method simultaneously.

• Ensures that each call to a synchronized method is run in a separate thread.

• Uses the object's intrinsic lock to prevent two threads from accessing the method simultaneously.

• Prevents objects outside the current package from accessing the method.

92. What is the default scope of a method?


• static

• public

• package-private

• private

• protected

93. When is an object's finalize method called?


• When System.gc() is called.

• When no references to the object exist in the application.

• Whenever the JVM's garbage collection algorithm decides to call it.

• When the object needs to release any resources it holds.

94. 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();


• Abstraction

• Encapsulation

• Inheritance

• Typecasting

• Polymorphism

95. If you need to determine exactly which class your object is:


• use the getClass() method.

• use the myClass property.

• use the instanceOf operator.

96. Which of the following can be abstract?


• Private Methods

• Static Methods

• All of these

• Constructors

• None of these

97. Which of the following *classes* include the getSession method used to retrieve an object that implements the HttpSession interface?


• HttpServletResponse

• Session Context

• SessionConfig

• HttpServletRequest

98. Can a HashMap contain a null key?


• No

• Yes

99. Which of the following is false regarding a class of a JavaBeans component?


• it is serializable.

• it is transient

• it has a public constructor with no arguments

• it is a public class

100. Which of these statements is correct?


• 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

• new and delete are keywords in the Java language

101. Which method is used to force one thread to wait for another thread to finish?


• stop()

• sleep(long milliseconds)

• join()

• yield()

102. Does Java provide any construct to find out the size of an object?


• No

• Yes, the sizeof operator

103. String x = "abc";  In this code, abc is:


• a Mutable String Literal

• an Immutable String Object

• a Mutable String Object

• an Immutable String Literal

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

105. Given the code: Integer i= new Integer("1"); if (i.toString() == i.toString()) System.out.println("Equal"); else System.out.println("Not Equal");


• Prints "Not Equal"

• Prints "Equal"

• Compiler error

• None of the above

106. 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;


• Double

• Long

• Byte

• Short

• Int

107. boolean b = 1 > 0 ? 1 < 0 : false;  What is the value of b?


• true

• false

• The code will not compile.

108. Which of the following APIs is used to create secure socket connections and manage digital certificates?


• Servlet




109. Can a top level class be private or protected?


• Yes

• No

110. 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};

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

112. What is the difference between static inner class and a non static inner class?


• 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 can only have static methods, an inner class may have non static methods.

• A static inner class has no reference to its parent class, a non static inner class does.

113. Which of the following statements is true?


• (1 << 31) == Integer.MAX_VALUE

• (-1 >> 1) == Integer.MAX_VALUE

• (1 >>> 1) == Integer.MAX_VALUE

• (-1 >>> 1) == Integer.MAX_VALUE

114. The keyword 'volatile' on a field is used in Java to:


• Guarantee that the field's current value is read, not a thread-cached value.

• Allow access to memory mapped devices (memory mapped I/O).

• Make the compiler aware that a variable will change frequently at runtime and allow the compiler to optimize for this.

115. Which of the following statements are true?


• (-1 >> 1) == Integer.MAX_VALUE

• (1 >>> 1) == Integer.MAX_VALUE

• (1 << 31) == Integer.MAX_VALUE

• (-1 >>> 1) == Integer.MAX_VALUE

• (1 <<< 31) == Integer.MAX_VALUE

116. An Enum implicitly implements which of the following interfaces?


• Set and Comparable

• Observer and Listener

• Iterable and Set

• Cloneable and Serializable

• Comparable and Serializable

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


• None of these

• Compilation error

• 0123

• 0122

118. What's the worst-case complexity of the function Arrays.sort(int[])?


• O(2^n)

• O(n*log(n))

• O(n)

• O(n^2)

119. Which of the following is true about overloading vs overriding methods?


• Overloading happens at compile time

• Final methods can be overriden, but not overloaded

• Overloading arbitrarily changes method access

• Overloaded methods must be the same data type

120. Which of the following is true about this Java snippet:  String a = "hello"; String b = "hello"; boolean x = (a == b);


• x can be true because of Java String interning.

• An exception is thrown because you cannot compare Strings this way.

• x is true because the String values are different.

• x is never true because you are comparing two different Objects.

121. Which one of the following statements is false?


• An abstract class may have a no-argument constructor.

• An abstract class may implement an interface without defining any of its methods.

• An abstract class cannot implement an interface.

• You can have member variables in an abstract class.

122. By which method does Java pass data?


• Both pass by reference and pass by value.

• Pass by value only.

• Pass by reference only.

123. Which java class provides variables local to each thread?


• ThreadLocal

• Thread

• LocalThread

• Runnable

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

• final

• initialized

• declared before the class

• primitives

125. Which of the following lines will not throw a compile time error?


• int a2[5];

• int []a1[] = new int[3][3];

• All throw compile time errors.

• int a2[4] = {3,4,5,6};

126. What is the difference between an inner class and a nested class?


• There is no difference; they are synonymous.

• A nested class is any class that is defined within another class. An inner class is a non-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 static nested class.

127. When using swing, which of the following is NOT a method on a JCheckBox object?


• checkb.setSelected(state);

• checkb.isSelected();

• checkb.addListener(Listener);

• checkb.addItemListener(item-listener);

128. How many bytes are in a long in Java?


• 4

• 8

• 16

• 32

• 2

129. In Java,  "const" is:


• a regular java keyword

• a reserved but unused keyword

• not a java keyword

130. How many objects are created: String s1="String";   String s2="String";   String s3="String";


• Two

• One

• Three

131. A java.util.ConcurrentModificationException can be thrown in a mono-threaded application.


• True

• False

132. Can a constructor be final?


• No

• Yes

133. 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 superclass defines additional constructors to its default, no-argument constructor.

• The subclass defines additional constructors to its default, no-argument constructor.

• The superclass is abstract.

134. During execution of code inside a "synchronized" statement, threads other than the executing one are prevented from:


• Acquiring the built-in lock associated with the object referenced by the synchronized statement

• Acquiring any locks currently held by the executing thread

• Making progress until the executing thread exits the block

• Accessing members of the object referenced by the synchronized statement

135. byte a = 64; byte b = (byte) (a << 2);  What is the value of b?


• 64

• 256

• -1

• 128

• 0

136. If I write System.exit (0); at the end of the try block, will the finally block still execute?


• Yes

• No

137. such construct in Java: class Foo {     {         // some code     } }


• is an instance initializer, additional to constructor and called before it

• is another way to define the constructor

• 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 after it

138. Add this annotation to your annotation declaration in order to ensure it's available for reflection.


• @Retention(RetentionPolicy.REFLECTION)

• @Runtime

• @Retention(RetentionPolicy.RUNTIME)

• @Target("RUNTIME")

• @Reflectable

139. Can you overload a static method signature?


• No

• Yes

140. True or false? StringBuilder is Thread-safe.


• True

• False

141. The default constructor of an enum type is implicitly:


• private

• protected

• public

142. Is it possible to start a thread twice?


• Yes

• No

143. 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(default="");

• String value() {return "";};

• String value("");

144. Which of these statements is TRUE for enums:


• All of the above.

• Enum can extend another enum.

• Enum can extend a class.

• Enum can implement an interface.