250+ TOP MCQs on Data Structures-HashMap and Answers

This set of Java Multiple Choice Questions & Answers (MCQs) on “Data Structures-HashMap”.

1. Map implements collection interface?
a) True
b) False

Answer: b
Clarification: Collection interface provides add, remove, search or iterate while map has clear, get, put, remove, etc.

2. Which of the below does not implement Map interface?
a) HashMap
b) Hashtable
c) EnumMap
d) Vector

Answer: d
Clarification: Vector implements AbstractList which internally implements Collection. Others come from implementing the Map interface.

3. What is the premise of equality for IdentityHashMap?
a) Reference equality
b) Name equality
c) Hashcode equality
d) Length equality

Answer: a
Clarification: 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: a
Clarification: HashMap always contains unique keys. If same key is inserted again, the new object replaces the previous object.

5. While finding the correct location for saving key value pair, how many times the key is hashed?
a) 1
b) 2
c) 3
d) unlimited till bucket is found

Answer: b
Clarification: 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: b
Clarification: 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: a
Clarification: 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());
d) Collections.synchronize(new HashMap());

Answer: c
Clarification: Collections.synchronizedMap() synchronizes entire map. ConcurrentHashMap provides thread safety without synchronizing entire map.

9. What will be the output of the following Java code snippet?

  1. public class Demo
  2. {
  3.   public static void main(String[] args)
  4.   {
  5. 		Map<Integer, Object> sampleMap = new TreeMap<Integer, Object>();
  6. 		sampleMap.put(1, null); 
  7. 		sampleMap.put(5, null); 
  8. 		sampleMap.put(3, null); 
  9. 		sampleMap.put(2, null); 
  10. 		sampleMap.put(4, null); 
  11.  
  12.        System.out.println(sampleMap);
  13.    }
  14. }

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: a
Clarification: 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: a
Clarification: BalancedTree will improve performance from O(n) to O(log n) by reducing hash collisions.

250+ TOP MCQs on Throw, Throws & Nested Try and Answers

Java MCQs on throw, throws & nested try of Java Programming Language.

1. Which of these keywords is used to generate an exception explicitly?
a) try
b) finally
c) throw
d) catch

Answer: c
Clarification: None.

2. Which of these class is related to all the exceptions that are explicitly thrown?
a) Error
b) Exception
c) Throwable
d) Throw

Answer: c
Clarification: None.

3. Which of these operator is used to generate an instance of an exception than can be thrown by using throw?
a) new
b) malloc
c) alloc
d) thrown

Answer: a
Clarification: new is used to create an instance of an exception. All of java’s built in run-time exceptions have two constructors: one with no parameters and one that takes a string parameter.

4. Which of these keywords is used to by the calling function to guard against the exception that is thrown by called function?
a) try
b) throw
c) throws
d) catch

Answer: c
Clarification: If a method is capable of causing an exception that it does not handle. It must specify this behaviour the behaviour so that callers of the method can guard themselves against that exception. This is done by using throws clause in methods declaration.

5. What will be the output of the following Java code?

  1.     class exception_handling 
  2.     {
  3.         public static void main(String args[]) 
  4.         {
  5.             try 
  6.             {
  7.                 int a = args.length;
  8.                 int b = 10 / a;
  9.                 System.out.print(a);
  10.                 try 
  11.                 {
  12.                     if (a == 1)
  13.                         a = a / a - a;
  14.                     if (a == 2) 
  15.                     {
  16.                         int []c = {1};
  17.                         c[8] = 9;
  18.                     }
  19.                 }
  20.                 catch (ArrayIndexOutOfBoundException e) 
  21.                 {
  22.                     System.out.println("TypeA");
  23.                 }
  24.                 catch (ArithmeticException e) 
  25.                 {
  26.                     System.out.println("TypeB");
  27.                 }
  28.             }
  29.         }
  30.     }

a) TypeA
b) TypeB
c) Compile Time Error
d) 0TypeB

Answer: c
Clarification: Because we can’t go beyond array limit

6. What will be the output of the following Java code?

  1.     class exception_handling 
  2.     {
  3.         public static void main(String args[]) 
  4.         {
  5.             try 
  6.             {
  7.                 System.out.print("A");
  8.                 throw new NullPointerException ("Hello");
  9.             }
  10.             catch(ArithmeticException e) 
  11.             {
  12.                 System.out.print("B");        	
  13.             }
  14.         }
  15.     }

a) A
b) B
c) Hello
d) Runtime Exception

Answer: d
Clarification: None.
Output:

$ javac exception_handling.java
$ java exception_handling
Exception in thread "main" java.lang.NullPointerException: Hello
	at exception_handling.main

7. What will be the output of the following Java code?

  1. public class San 
  2.  {  
  3.     public static void main(String[] args) 
  4.     {
  5.         try 
  6.         { 
  7.             return; 
  8.         } 
  9.         finally 
  10.         {
  11.             System.out.println( "Finally" ); 
  12.         } 
  13.     } 
  14. }

a) Finally
b) Compilation fails
c) The code runs with no output
d) An exception is thrown at runtime

Answer: a
Clarification: Because finally will execute always.

8. What will be the output of the following Java code?

  1. public class San 
  2. {
  3.     public static void main(String args[])
  4.     {
  5.         try 
  6.         {
  7.             System.out.print("Hello world ");
  8.         }
  9.         finally 
  10.         {
  11.             System.out.println("Finally executing ");
  12.         }
  13.     }
  14. }

a) The program will not compile because no exceptions are specified
b) The program will not compile because no catch clauses are specified
c) Hello world
d) Hello world Finally executing

Answer: d
Clarification: None

250+ TOP MCQs on Event Handling Basics and Answers

Java MCQs on basics of event handling in Java Programming Language.

1. Which of these packages contains all the classes and methods required for even handling in Java?
a) java.applet
b) java.awt
c) java.event
d) java.awt.event

Answer: d
Clarification: Most of the event to which an applet response is generated by a user. Hence they are in Abstract Window Kit package, java.awt.event.

2. What is an event in delegation event model used by Java programming language?
a) An event is an object that describes a state change in a source
b) An event is an object that describes a state change in processing
c) An event is an object that describes any change by the user and system
d) An event is a class used for defining object, to create events

Answer: a
Clarification: An event is an object that describes a state change in a source.

3. Which of these methods are used to register a keyboard event listener?
a) KeyListener()
b) addKistener()
c) addKeyListener()
d) eventKeyboardListener()

Answer: c
Clarification: None.

4. Which of these methods are used to register a mouse motion listener?
a) addMouse()
b) addMouseListener()
c) addMouseMotionListner()
d) eventMouseMotionListener()

Answer: c
Clarification: None.

5. What is a listener in context to event handling?
a) A listener is a variable that is notified when an event occurs
b) A listener is a object that is notified when an event occurs
c) A listener is a method that is notified when an event occurs
d) None of the mentioned

Answer: b
Clarification: A listener is a object that is notified when an event occurs. It has two major requirements first, it must have been registered with one or more sources to receive notification about specific event types, and secondly it must implement methods to receive and process these notifications.

6. Event class is defined in which of these libraries?
a) java.io
b) java.lang
c) java.net
d) java.util

Answer: d
Clarification: None.

7. Which of these methods can be used to determine the type of event?
a) getID()
b) getSource()
c) getEvent()
d) getEventObject()

Answer: a
Clarification: getID() can be used to determine the type of an event.

8. Which of these class is super class of all the events?
a) EventObject
b) EventClass
c) ActionEvent
d) ItemEvent

Answer: a
Clarification: EventObject class is a super class of all the events and is defined in java.util package.

9. Which of these events will be notified if scroll bar is manipulated?
a) ActionEvent
b) ComponentEvent
c) AdjustmentEvent
d) WindowEvent

Answer: c
Clarification: AdjustmentEvent is generated when a scroll bar is manipulated.

10. Which of these events will be generated if we close an applet’s window?
a) ActionEvent
b) ComponentEvent
c) AdjustmentEvent
d) WindowEvent

Answer: d
Clarification: WindowEvent is generated when a window is activated, closed, deactivated, deiconfied, iconfied, opened or quit.

Global Education & Learning Series – Java Programming Language.

250+ TOP MCQs on Liskov’s Principle and Answers

This set of Java Questions and Answers for Campus interviews on “Liskov’s Principle”.

1. What does Liskov substitution principle specify?
a) parent class can be substituted by child class
b) child class can be substituted by parent class
c) parent class cannot be substituted by child class
d) No classes can be replaced by each other

Answer: a
Clarification: Liskov substitution principle states that Objects in a program should be replaceable with instances of their sub types without altering the correctness of that program.

advertisement

2. What will be the correct option of the following Java code snippet?

  1. interface ICust 
  2. {
  3. }
  4. class RegularCustomer implements ICust 
  5. {
  6. }
  7. class OneTimeCustomer implements ICust 
  8. {
  9. }

a) ICust can be replaced with RegularCustomer
b) RegularCustomer can be replaced with OneTimeCustomer
c) OneTimeCustomer can be replaced with RegularCustomer
d) We can instantiate objects of ICust

Answer: a
Clarification: According to Liskov substitution principle we can replace ICust with RegularCustomer or OneTimeCustomer without affecting functionality.

3. What will be the output of the following Java code snippet?

  1. public class Shape 
  2. {
  3. 	public int area()
  4.         {
  5. 		return 1;
  6. 	}
  7. }
  8. public class Square extends Shape 
  9. {
  10. 	public int area()
  11.         {
  12. 		return 2;
  13. 	}
  14. }
  15. class Main() 
  16. {
  17.    public static void main(String[] args)
  18.    {
  19. 	Shape shape = new Shape();
  20. 	Square square = new Square();
  21. 	shape = square;
  22. 	System.out.println(shape.area());
  23.     }
  24. }

a) Compilation failure
b) Runtime failure
c) 1
d) 2

Answer: d
Clarification: Child object can be assigned to parent variable without change in behaviour.

advertisement

4. What will be the output of the following Java code snippet?

  1. public class Shape 
  2. {
  3. 	public int area()
  4.         {
  5. 		return 1;
  6. 	}
  7. }
  8. public class Rectangle extends Shape 
  9. {
  10. 	public int area()
  11.         {
  12. 		return 3;
  13. 	}
  14. }
  15. class Main() 
  16. {
  17.    public static void main(String[] args)
  18.    {
  19. 	Shape shape = new Shape();
  20. 	Rectangle rect = new Rectangle();
  21. 	shape = rect;
  22. 	System.out.println(shape.area());
  23.    }
  24. }

a) Compilation failure
b) 3
c) 1
d) 2

Answer: b
Clarification: Child object can be assigned to parent variable without change in behaviour.

5. What will be the output of the following Java code?

  1. public class Shape 
  2. {
  3. 	public int area()
  4.         {
  5. 		return 1;
  6. 	}
  7. }
  8. public class Square extends Shape 
  9. {
  10. 	public int area()
  11.         {
  12. 		return 2;
  13. 	}
  14. }
  15. class Main() 
  16. {
  17.    public static void main(String[] args)
  18.    {
  19. 	Shape shape = new Shape();
  20. 	Square square = new Square();
  21. 	square = shape;
  22. 	System.out.println(square.area());
  23.    }
  24. }

a) Compilation failure
b) 3
c) 1
d) 2

Answer: a
Clarification: Parent object cannot be assigned to child class.

6. What will be the output of the following Java code?

advertisement

  1. public class Shape 
  2. {
  3. 	public int area()
  4.         {
  5. 		return 1;
  6. 	}
  7. }
  8. public class Square extends Shape 
  9. {
  10. 	public int area()
  11.         {
  12. 		return 2;
  13. 	}
  14. }
  15. public class Rectangle extends Shape 
  16. {
  17. 	public int area()
  18.         {
  19. 		return 3;
  20. 	}
  21. }
  22. class Main() 
  23. {
  24.    public static void main(String[] args)
  25.    {
  26. 	Shape shape = new Shape();
  27. 	Square square = new Square();
  28.     	Rectangle rect = new Rectangle();
  29. 	rect = (Rectangle)shape;
  30. 	System.out.println(square.area());
  31.    }
  32. }

a) Compilation failure
b) 3
c) Runtime Exception
d) 2

Answer: c
Clarification: ClassCastException is thrown as we cannot assign parent object to child variable.

7. What will be the output of the following Java code?

  1. public class Shape 
  2. {
  3. 	public int area()
  4.         {
  5. 		return 1;
  6. 	}
  7. }
  8. public class Square extends Shape 
  9. {
  10. 	public int area()
  11.         {
  12. 		return 2;
  13. 	}
  14. }
  15. public class Rectangle extends Shape 
  16. {
  17. 	public int area()
  18.         {
  19. 		return 3;
  20. 	}
  21. }
  22. class Main() 
  23. {
  24.       public static void main(String[] args)
  25.       {
  26. 	 Shape shape = new Shape();
  27. 	 Square square = new Square();
  28.    	 Rectangle rect = new Rectangle();
  29. 	 rect = (Rectangle)square;
  30. 	 System.out.println(square.area());
  31.       }
  32. }

a) Compilation failure
b) 3
c) Runtime Exception
d) 2

Answer: a
Clarification: We cannot assign one child class object to another child class variable.

  1. interface Shape 
  2. {
  3. 	public int area();
  4. }
  5. public class Square implements Shape 
  6. {
  7. 	public int area()
  8.         {
  9. 		return 2;
  10. 	}
  11. }
  12. public class Rectangle implements Shape 
  13. {
  14. 	public int area()
  15.         {
  16. 		return 3;
  17. 	}
  18. }

8. What will be the output of the following Java code?

  1. public class Shape 
  2. {
  3. 	public int area()
  4.         {
  5. 		return 1;
  6. 	}
  7. }
  8. public class Square extends Shape 
  9. {
  10. 	public int area()
  11.         {
  12. 		return 2;
  13. 	}
  14. }
  15. public class Rectangle extends Shape 
  16. {
  17. 	public int area()
  18.         {
  19. 		return 3;
  20. 	}
  21. }
  22. class Main() 
  23. {
  24.        public static void main(String[] args)
  25.        {
  26. 	 Shape shape = new Shape();
  27. 	 Square square = new Square();
  28.    	 Rectangle rect = new Rectangle();
  29. 	 rect = (Rectangle)square;
  30. 	 System.out.println(square.area());
  31. 	}
  32. }

a) Compilation failure
b) 3
c) Runtime Exception
d) 2

Answer: a
Clarification: Interface cannot be instantiated. So we cannot create instances of shape.

advertisement

9. What will be the output of the following Java code?

  1. public class Shape 
  2. {
  3. 	public int area()
  4.         {
  5. 		return 1;
  6. 	}
  7. }
  8. public class Square extends Shape 
  9. {
  10. 	public int area()
  11.         {
  12. 		return 2;
  13. 	}
  14. }
  15. public class Rectangle extends Shape 
  16. {
  17. 	public int area()
  18.         {
  19. 		return 3;
  20. 	}
  21. }
  22. public static void main(String[] args)
  23. {
  24. 	 Shape shape = new Square();
  25.    	 shape = new Rectangle();
  26. 	 System.out.println(shape.area());
  27. }

a) Compilation failure
b) 3
c) Runtime Exception
d) 2

Answer: b
Clarification: With parent class variable we can access methods declared in parent class. If the parent class variable is assigned child class object than it accesses the method of child class.

10. What will be the output of the following Java code?

  1. public class Shape 
  2. {
  3. 	public int area()
  4.         {
  5. 		return 1;
  6. 	}
  7. }
  8. public class Square extends Shape 
  9. {
  10. 	public int area()
  11.         {
  12. 		return 2;
  13. 	}
  14. }
  15. public class Rectangle extends Shape 
  16. {
  17. 	public int area()
  18.         {
  19. 		return 3;
  20. 	}
  21. }
  22. public static void main(String[] args)
  23. {
  24. 	 Shape square = new Square();
  25.    	 Shape rect = new Rectangle();
  26.      	 square = rect;
  27. 	 System.out.println(square.area());
  28. }

a) Compilation failure
b) 3
c) Runtime Exception
d) 2

Answer: b
Clarification: The method of the child class object is accessed. When we reassign objects, the methods of the latest assigned object are accessed.

Java for Campus Interviews, here is complete set on Multiple Choice Questions and Answers on Java.

contest

» Next – Java Questions & Answers – Coding best practices

Advanced 250+ TOP MCQs on Reflection API and Answers

This set of Advanced Java Multiple Choice Questions & Answers (MCQs) on “Reflection API”.

1. What are the components of a marker interface?
a) Fields and methods
b) No fields, only methods
c) Fields, no methods
d) No fields, No methods

Answer: d
Clarification: Marker interface in Java is an empty interface in Java.

2. Which of the following is not a marker interface?
a) Serializable
b) Cloneable
c) Remote
d) Reader

Answer: d
Clarification: Reader is not a marker interface. Serializable, Cloneable and Remote interfaces are marker interface.

3. What is not the advantage of Reflection?
a) Examine a class’s field and method at runtime
b) Construct an object for a class at runtime
c) Examine a class’s field at compile time
d) Examine an object’s class at runtime

Answer: c
Clarification: Reflection inspects classes, interfaces, fields and methods at a runtime.

4. How private method can be called using reflection?
a) getDeclaredFields
b) getDeclaredMethods
c) getMethods
d) getFields

Answer: b
Clarification: getDeclaredMethods gives instance of java.lang.reflect.Method.

5. How private field can be called using reflection?
a) getDeclaredFields
b) getDeclaredMethods
c) getMethods
d) getFields

Answer: a
Clarification: getDeclaredFields gives instance of java.lang.reflect.Fields.

6. What is used to get class name in reflection?
a) getClass().getName()
b) getClass().getFields()
c) getClass().getDeclaredFields()
d) new getClass()

Answer: a
Clarification: getClass().getName() is used to get a class name from object in reflection.

7. How method can be invoked on unknown object?
a) obj.getClass().getDeclaredMethod()
b) obj.getClass().getDeclaredField()
c) obj.getClass().getMethod()
d) obj.getClass().getObject()

Answer: c
Clarification: obj.getClass().getMethod is used to invoke a method on unknown object obj.

8. How to get the class object of associated class using Reflection?
a) Class.forName(“className”)
b) Class.name(“className”)
c) className.getClass()
d) className.getClassName()

Answer: a
Clarification: forName(String className) returns the Class object associated with the class or interface with the given string name.

9. What does Class.forName(“myreflection.Foo”).getInstance() return?
a) An array of Foo objects
b) class object of Foo
c) Calls the getInstance() method of Foo class
d) Foo object

Answer: d
Clarification: Class.forName(“myreflection.Foo”) returns the class object of Foo and getInstance() would return a new object.

10. What does foo.getClass().getMethod(“doSomething”, null) return?
a) doSomething method instance
b) Method is returned and we can call the method as method.invoke(foo,null);
c) Class object
d) Exception is thrown

Answer: b
Clarification: foo.getClass().getMethod() returns a method and we can call the method using method.invoke();

250+ TOP MCQs on Data Type-BigDecimal and Answers

This set of Tough Java Questions and Answers on “Data Type-BigDecimal”.

1. Which of the following is the advantage of BigDecimal over double?
a) Syntax
b) Memory usage
c) Garbage creation
d) Precision

Answer: d
Clarification: BigDecimal has unnatural syntax, needs more memory and creates a great amount of garbage. But it has a high precision which is useful for some calculations like money.

2. Which of the below data type doesn’t support overloaded methods for +,-,* and /?
a) int
b) float
c) double
d) BigDecimal

Answer: d
Clarification: int, float, double provide overloaded methods for +,-,* and /. BigDecimal does not provide these overloaded methods.

3. What will be the output of the following Java code snippet?

  1.    double a = 0.02;
  2.    double b = 0.03;
  3.    double c = b - a;
  4.    System.out.println(c);
  5.  
  6.    BigDecimal _a = new BigDecimal("0.02");
  7.    BigDecimal _b = new BigDecimal("0.03");
  8.    BigDecimal _c = b.subtract(_a);
  9.    System.out.println(_c);

a)

   0.009999999999999998
   0.01

b)

   0.01
   0.009999999999999998

c)

   0.01
   0.01

d)

   0.009999999999999998
   0.009999999999999998

Answer: a
Clarification: BigDecimal provides more precision as compared to double. Double is faster in terms of performance as compared to BigDecimal.

 
 

4. What is the base of BigDecimal data type?
a) Base 2
b) Base 8
c) Base 10
d) Base e

Answer: c
Clarification: A BigDecimal is n*10^scale where n is an arbitrary large signed integer. Scale can be thought of as the number of digits to move the decimal point to left or right.

5. What is the limitation of toString() method of BigDecimal?
a) There is no limitation
b) toString returns null
c) toString returns the number in expanded form
d) toString uses scientific notation

Answer: d
Clarification: toString() of BigDecimal uses scientific notation to represent numbers known as canonical representation. We must use toPlainString() to avoid scientific notation.

6. Which of the following is not provided by BigDecimal?
a) scale manipulation
b) + operator
c) rounding
d) hashing

Answer: b
Clarification: toBigInteger() converts BigDecimal to a BigInteger.toBigIntegerExact() converts this BigDecimal to a BigInteger by checking for lost information.

7. BigDecimal is a part of which package?
a) java.lang
b) java.math
c) java.util
d) java.io

Answer: b
Clarification: BigDecimal is a part of java.math. This package provides various classes for storing numbers and mathematical operations.

8. What is BigDecimal.ONE?
a) wrong statement
b) custom defined statement
c) static variable with value 1 on scale 10
d) static variable with value 1 on scale 0

Answer: d
Clarification: BigDecimal.ONE is a static variable of BigDecimal class with value 1 on scale 0.

9. Which class is a library of functions to perform arithmetic operations of BigInteger and BigDecimal?
a) MathContext
b) MathLib
c) BigLib
d) BigContext

Answer: a
Clarification: MathContext class is a library of functions to perform arithmetic operations of BigInteger and BigDecimal.

10. What will be the output of the following Java code snippet?

  1. public class AddDemo 
  2. {
  3. 	public static void main(String args[]) 
  4.         {
  5. 		BigDecimal b = new BigDecimal("23.43");
  6. 		BigDecimal br = new BigDecimal("24");
  7. 		BigDecimal bres = b.add(new BigDecimal("450.23"));
  8. 		System.out.println("Add: "+bres);
  9.  
  10. 		MathContext mc = new MathContext(2, RoundingMode.DOWN);
  11. 		BigDecimal bdecMath = b.add(new BigDecimal("450.23"), mc);
  12. 		System.out.println("Add using MathContext: "+bdecMath);
  13. 	}
  14. }

a) Compilation failure
b)

Add: 473.66
Add using MathContext: 4.7E+2

c)

Add 4.7E+2
Add using MathContext: 473.66

d) Runtime exception

Answer: b
Clarification: add() adds the two numbers, MathContext provides library for carrying out various arithmetic operations.

To practice tough questions and answers on all areas of Java, here is complete set on Multiple Choice Questions and Answers on Java.

contest