Java MCQ Set 1
1. What is true about private constructor?
a) Private constructor ensures only one instance of a class exist at any point of time
b) Private constructor ensures multiple instances of a class exist at any point of time
c) Private constructor eases the instantiation of a class
d) Private constructor allows creating objects in other classes
Answer
Answer: a [Reason:] Object of private constructor can only be createed withing class. Private constructor is used in singleton pattern.
2. What would be the behaviour if this() and super() used in a method?
a) Runtime error
b) Throws exception
c) compile time error
d) Runs successfully
Answer
Answer: c [Reason:] this() and super() cannot be used in a method. This throws compile time error.
3. What is false about constructor?
a) Constructors cannot be synchronized in Java
b) Java does not provide default copy constructor
c) Constructor can be overloaded
d) “this” and “super” can be used in a constructor
Answer
Answer: c [Reason:] Default, parameterised constructors can be defined.
4. What is true about Class.getInstance()?
a) Class.getInstance calls the constructor
b) Class.getInstance is same as new operator
c) Class.getInstance needs to have matching constructor
d) Class.getInstance creates object if class does not have any constructor
Answer
Answer: d [Reason:] Class class provides list of methods for use like getInstance().
5. What is true about constructor?
a) It can contain return type
b) It can take any number of parameters
c) It can have any non access modifiers
d) Constructor cannot throw exception
Answer
Answer: b [Reason:] Constructor returns a new object with variables defined as in the class. Instance variables are newly created and only one copy of static variables are created.
6. Abstract class cannot have a constructor.
a) True
b) False
Answer
Answer: b [Reason:] No instance can be created of abstract class. Only pointer can hold instance of object.
7. What is true about protected constructor?
a) Protected constructor can be called directly
b) Protected constructor can only be called using super()
c) Protected constructor can be used outside package
d) protected constructor can be instantiated even if child is in a differnt package
Answer
Answer: b [Reason:] Protected access modifier means that constructor can be accessed by child classes of the parent class and classes in the same package.
8. What is not the use of “this” keyword in Java?
a) Passing itself to another method
b) Calling another constructor in constructor chaining
c) Referring to the instance variable when local variable has the same name
d) Passing itself to method of the same class
Answer
Answer: d [Reason:] “this” is an important keyword in java. It helps to distinguish between local variable and variables passed in the method as parameters.
9. What would be the behaviour if one parameterized constructor is explicitly defined?
a) Compilation error
b) Compilation succeeds
c) Runtime error
d) Compilation succeeds but at the time of creating object using default constructor, it throws compilation error
Answer
Answer: d [Reason:] The class compiles successfully. But the object creation of that class gives compilation error.
10. What would be behaviour if constructor has a return type?
a) Compilation error
b) Runtime error
c) Compilation and runs successfully
d) Only String return type is allowed
Answer
Answer: a [Reason:]The constructor cannot have a return type. It should create and return new object. Hence it would give compilation error.
Java MCQ Set 2
1. What would be the output of the following codesnippet if variable a=10?
-
if(a<=0)
-
{
-
if(a==0)
-
{
-
System.out.println("1 ");
-
}
-
else
-
{
-
System.out.println("2 ");
-
}
-
}
-
System.out.println("3 ");
a) 1 2
b) 2 3
c) 1 3
d) 3
Answer
Answer: d [Reason:] Since the first if condition is not met, control would not go inside if statement and hence only statement after the entire if block will be executed.
2. The while loop repeats a set of code while the condition is not met?
a) True
b) False
Answer
Answer: b [Reason:] While loop repeats a set of code only until condition is met.
3. What is true about break?
a) Break stops the execution of entire program
b) Break halts the execution and forces the control out of the loop
c) Break forces the control out of the loop and starts the execution of next iteration.
d) Break halts the execution of the loop for certain time frame
Answer
Answer: b [Reason:] Break halts the execution and forces the control out of the loop.
4. What is true about do statement?
a) do statement executes the code of a loop at least once
b) do statement does not get execute if condition is not matched in the first iteration
c) do statement checks the condition at the beginning of the loop
d) do statement executes the code more than once always
Answer
Answer: a [Reason:] Do statement checks the condition at the end of the loop. Hence, code gets executed at least once.
5. Which of the following is used with switch statement?
a) Continue
b) Exit
c) break
d) do
Answer
Answer: c [Reason:] Break is used with switch statement to shift control out of switch.
6. What is the valid data type for variable “a” to print “Hello World”?
-
switch(a)
-
{
-
System.out.println("Hello World");
-
}
a) int and float
b) byte and short
c) char and long
d) byte and char
Answer
Answer: d [Reason:] The switch condition would only meet if variable “a” is of type byte or char.
7. Which of the following is not a decision making statement?
a) if
b) if-else
c) switch
d) do-while
Answer
Answer: d [Reason:] do-while is an iteration statement. Others are decision making statements.
8. Which of the following is not a valid jump statement?
a) break
b) goto
c) continue
d) return
Answer
Answer: b [Reason:] break, continue and return transfer control to another part of the program and returns back to caller after execution. However, goto is marked as not used in Java.
9. From where break statement causes an exit?
a) Only from innermost loop
b) Terminates a program
c) Only from innermost switch
d) From innermost loops or switches
Answer
Answer: d [Reason:] The break statement causes an exit from innermost loop or switch.
10. Which of the following is not a valid flow control statement?
a) exit()
b) break
c) continue
d) return
Answer
Answer: a [Reason:] exit() is not a flow control statement in Java. exit() terminates the currently running JVM.
Java MCQ Set 3
1. Map implements collection interface?
a) True
b) False
Answer
Answer: b [Reason:] Collection interface provides add, remove, search or iterate while map has clear, get, put, remove, etc.
2. Which of the below doesnt implement Map interface?
a) HashMap
b) Hashtable
c) EnumMap
d) Vector
Answer
Answer: d [Reason:] Vector implements AbstractList which internally implements Collection. Others come from implementing Map interface.
3. What is the premise of equality for IdentityHashMap?
a) Reference equality
b) Name equality
c) Hashcode equality
d) Length equality
Answer
Answer: a [Reason:] IdentityHashMap is rarely used as it violates the basic contract of implementing equals() and hashcode() method.
4. What happens if we put a key object in a HashMap which exists?
a) The new object replaces the older object
b) The new object is discarded
c) The old object is removed from the map
d) It throws an exception as the key already exists in the map
Answer
Answer: a [Reason:] HashMap always contains unique keys. If same key is inserted again, the new object replaces the previous object.
5. While finding correct location for saving key value pair, how many times key is hashed?
a) 1
b) 2
c) 3
d) unlimited till bucket is found
Answer
Answer: b [Reason:] The key is hashed twice; first by hashCode() of Object class and then by internal hashing method of HashMap class.
6. Is hashmap an ordered collection?
a) True
b) False
Answer
Answer: b [Reason:] Hashmap outputs in the order of hashcode of the keys. So it is unordered but will always have same result for same set of keys.
7. If two threads access the same hashmap at the same time, what would happen?
a) ConcurrentModificationException
b) NullPointerException
c) ClassNotFoundException
d) RuntimeException
Answer
Answer: a [Reason:] The code will throw ConcurrentModificationException if two threads access the same hashmap at the same time.
8. How to externally synchronize hashmap?
a) HashMap.synchronize(HashMap a);
b) HashMap a = new HashMap();
a.synchronize();
c) Collections.synchronizedMap(new HashMap<String, String>());
d) Collections.synchronize(new HashMap<String, String>());
Answer
Answer: c [Reason:] Collections.synchronizedMap() synchronizes entire map. ConcurrentHashMap provides thread safety without synchronizing entire map.
9. What is the output of below snippet?
-
public class Demo
-
{
-
public static void main(String[] args)
-
{
-
Map<Integer, Object> sampleMap = new TreeMap<Integer, Object>();
-
sampleMap.put(1, null);
-
sampleMap.put(5, null);
-
sampleMap.put(3, null);
-
sampleMap.put(2, null);
-
sampleMap.put(4, null);
-
-
System.out.println(sampleMap);
-
}
-
}
a) {1=null, 2=null, 3=null, 4=null, 5=null}
b) {5=null}
c) Exception is thrown
d) {1=null, 5=null, 3=null, 2=null, 4=null}
Answer
Answer: a [Reason:] HashMap needs unique keys. TreeMap sorts the keys while storing objects.
10. If large number of items are stored in hash bucket, what happens to the internal structure?
a) The bucket will switch from LinkedList to BalancedTree
b) The bucket will increase its size by a factor of load size defined
c) The LinkedList will be replaced by another hashmap
d) Any further addition throws Overflow exception
Answer
Answer: a [Reason:] BalancedTree will improve performance from O(n) to O(log n) by reducing hash collisions.
Java MCQ Set 4
1. How can we remove an object from ArrayList?
a) remove() method
b) using Iterator
c) remove() method and using Iterator
d) delete() method
Answer
Answer: c [Reason:] There are 2 ways to remove an object from ArrayList. We can use overloaded method remove(int index) or remove(Object obj). We can also use an Iterator to remove the object.
2. How to remove duplicates from List?
a) HashSet<String> listToSet = new HashSet<String>(duplicateList);
b) HashSet<String> listToSet = duplicateList.toSet();
c) HashSet<String> listToSet = Collections.convertToSet(duplicateList);
d) HashSet<String> listToSet = duplicateList.getSet();
Answer
Answer: a [Reason:] Duplicate elements are allowed in List. Set contains unique objects.
3. How to sort elements of ArrayList?
a) Collection.sort(listObj);
b) Collections.sort(listObj);
c) listObj.sort();
d) Sorter.sortAsc(listObj);
Answer
Answer: b [Reason:] Collections provides a method to sort the list. The order of sorting can be defined using Comparator.
4. When two threads access the same ArrayList object what is the outcome of program?
a) Both are able to access the object
b) ConcurrentModificationException is thrown
c) One thread is able to access the object and second thread hets NullPointer exception
d) One thread is able to access the object and second thread will wait till control is passed to second one
Answer
Answer: b [Reason:] ArrayList is not synchronized. Vector is the synchronized data structure.
5. How is Arrays.asList() different than the standard way of initialising List?
a) Both are same
b) Arrays.asList() throws compilation error
c) Arrays.asList() returns a fixed length list and doesn’t allow to add or remove elements
d) We cannot access the list returned using Arrays.asList()
Answer
Answer: c [Reason:] List returned by Arrays.asList() is a fixed length list which doesn’t allow us to add or remove element from it.add() and remove() method will throw UnSupportedOperationException if used.
6. What is the difference between length() and size() of ArrayList?
a) length() and size() return the same value
b) length() is not defined in ArrayList
c) size() is not defined in ArrayList
d) length() returns the capacity of ArrayList and size() returns the actual number of elements stored in the list
Answer
Answer: d [Reason:] length() returns the capacity of ArrayList and size() returns the actual number of elements stored in the list which is always less than or equal to capacity.
7. Which class provides thread safe implementation of List?
a) ArrayList
b) CopyOnWriteArrayList
c) HashList
d) List
Answer
Answer: b [Reason:] CopyOnWriteArrayList is a concurrent collection class. Its very efficient if ArrayList is mostly used for reading purpose, because it allows multiple threads to read data without locking, which was not possible with synchronized ArrayList.
8. Which of the below is not an implementation of List interface?
a) RoleUnresolvedList
b) Stack
c) AttibuteList
d) SessionList
Answer
Answer: d [Reason:] SessionList is not an implementation of List interface. The others are concrete classes of List.
9. What is the worst case complexity of accessing an element in ArrayList?
a) O(n)
b) O(1)
c) O(nlogn)
d) O(2)
Answer
Answer: b [Reason:] ArrayList has O(1) complexity for accessing an element in ArrayList. O(n) is the complexity for accessing an element from LinkedList.
10. When an array is passed to a method, will the content of the array undergo changes with the actions carried within the function?
a) True
b) False
Answer
Answer: a [Reason:] If we make a copy of array before any changes to the array the content will not change. Else the content of the array will undergo changes.
-
public void setMyArray(String[] myArray)
-
{
-
if(myArray == null)
-
{
-
this.myArray = new String[0];
-
}
-
else
-
{
-
this.myArray = Arrays.copyOf(newArray, newArray.length);
-
}
-
}
Java MCQ Set 5
1. What is the default clone of HashSet?
a) Deep clone
b) Shallow clone
c) Plain clone
d) Hollow clone
Answer
Answer: b [Reason:] Default clone() method uses shallow copy. The internal elements are not cloned. A shallow copy only copies the reference object.
2. Do we have get(Object o) method in HashSet?
a) True
b) False
Answer
Answer: b [Reason:] get(Object o) method is useful when we want to compare objects based on comparision of values. HashSet does not provide any way to compare objects. It just gurantees unique objects stored in the collection.
3. What does Collections.emptySet() return?
a) Immutable Set
b) Mutable Set
c) The type of Set depends on the parameter passed to the emptySet() method
d) Null object
Answer
Answer: a [Reason:] Immutable Set is useful in multithreaded environment. One does not need to declare generic type collection. It is inferred by the context of method call.
4. What is the initial capacity and load factor of HashSet?
a) 10, 1.0
b) 32, 0.75
c) 16, 0.75
d) 32, 1.0
Answer
Answer: c [Reason:] We should not set the initial capacity too high and load factor too low if iteration performance is needed.
5. What is the relation between hashset and hashmap?
a) HashSet internally implements HashMap
b) HashMap internally implements HashSet
c) HashMap is the interface; HashSet is the concrete class
d) HashSet is the interface; HashMap is the concrete class
Answer
Answer: a [Reason:] HashSet is implemented to provide uniqueness feature which is not provided by HashMap. This also reduces code duplication and provides the memory efficient behavior of HashMap.
6. What is the output of below code snippet?
-
public class Test
-
{
-
public static void main(String[] args)
-
{
-
Set s = new HashSet();
-
s.add(new Long(10));
-
s.add(new Integer(10));
-
for(Object object : s)
-
{
-
System.out.println("test - "+object);
-
}
-
}
-
}
a) Test – 10
Test – 10
b) Test – 10
c) Runtime Exception
d) Compilation Failure
Answer
Answer: a [Reason:] Integer and Long are two different datatyoes and different objects. So they will be treated as unique elements and not overridden.
7. Set has contains(Object o) method?
a) True
b) False
Answer
Answer: a [Reason:] Set has contains(Object o) method instead of get(Object o) method as get is needed for comparing object and getting corresponding value.
8. What is the difference between TreeSet and SortedSet?
a) TreeSet is more efficient than SortedSet
b) SortedSet is more efficient than TreeSet
c) TreeSet is an interface; SortedSet is a concrete class
d) SortedSet is an interface; TreeSet is a concrete class
Answer
Answer: d [Reason:] SortedSet is an interface. It maintains an ordered set of elements. TreeSet is an implementation of SortedSet.
9. What happens if two threads simultaneously modify TreeSet?
a) ConcurrentModificationException is thrown
b) Both threads can perform action successfully
c) FailFastException is thrown
d) IteratorModificationException is thrown
Answer
Answer: a [Reason:] TreeSet provides fail-fast iterator. Hence when concurrently modifying TreeSet it throws ConcurrentModificationException.
10. What is the unique feature of LinkedHashSet?
a) It is not a valid class
b) It maintains the insertion order and guarantees uniqueness
c) It provides a way to store key values with uniqueness
d) The elements in the collection are linked to each other
Answer
Answer: b [Reason:] Set is a collection of unique elements.HashSet has the behavior of Set and stores key value pairs. The LinkedHashSet stores the key value pairs in the order of insertion.