Java Interview Questions MCQs

1 min read

Preparing for technical interviews requires a deep understanding of object-oriented programming paradigms, memory management, runtime behavior, and modern language enhancements. Java technical assessments typically probe foundational components such as the Java Virtual Machine (JVM), exception lifecycles, concurrency models, and the internal mechanics of data structures like HashMaps. Mastering these concepts ensures developers can write secure, scalable, and high-performance enterprise applications while confidently navigating rigorous technical evaluations.

1. Which component is responsible for converting Java bytecode into machine-specific code?

a) Java Compiler
b) Java Virtual Machine (JVM)
c) Java Runtime Environment (JRE)
d) Java Development Kit (JDK)
Correct Answer: b) Java Virtual Machine (JVM)
Explanation:
The JVM is the engine that drives the Java code. It converts Java bytecode into machine-specific instructions.

2. What is the primary difference between JRE and JDK?

a) JDK contains only the JVM, while JRE contains development tools
b) JRE is used to develop applications, while JDK is used to run them
c) JDK contains JRE and development tools, while JRE provides the environment to run Java applications
d) There is no difference between JRE and JDK
Correct Answer: c) JDK contains JRE and development tools, while JRE provides the environment to run Java applications
Explanation:
The JDK is a full-featured software development kit for Java, including the JRE, compilers, and tools.

3. Why is the main method in Java declared as static?

a) So that it can be overloaded
b) Because it returns an integer value
c) So that the JVM can invoke it without instantiating the class
d) To allow multiple threads to access it simultaneously
Correct Answer: c) So that the JVM can invoke it without instantiating the class
Explanation:
The JVM needs to call the main method before any objects are created. Declaring it static allows it to be invoked on the class itself.

4. Which of the following modifiers cannot be used with a top-level class?

a) public
b) abstract
c) final
d) private
Correct Answer: d) private
Explanation:
A top-level class cannot be private or protected. Only nested inner classes can have these access modifiers.

5. What happens if you declare a variable as final in Java?

a) Its value can be changed by subclasses
b) Its value cannot be modified once initialized
c) It can only be accessed statically
d) It is automatically initialized to zero
Correct Answer: b) Its value cannot be modified once initialized
Explanation:
A final variable acts as a constant in Java. Once a value is assigned, it cannot be reassigned.

6. Which data type is returned by the hashCode() method in the Object class?

a) long
b) int
c) String
d) short
Correct Answer: b) int
Explanation:
The hashCode() method returns an integer representation of the object memory address or value, used in hashing data structures.

7. Why are Strings immutable in Java?

a) To allow String manipulation
b) To save memory space in the String pool and provide thread safety
c) To prevent garbage collection
d) Because they are primitive types
Correct Answer: b) To save memory space in the String pool and provide thread safety
Explanation:
Immutability allows Java to cache String literals securely in the String pool, improving memory efficiency.

8. What is the key difference between StringBuilder and StringBuffer?

a) StringBuffer is synchronized, while StringBuilder is not
b) StringBuilder is synchronized, while StringBuffer is not
c) StringBuffer is immutable, while StringBuilder is mutable
d) StringBuilder is thread-safe, while StringBuffer is not
Correct Answer: a) StringBuffer is synchronized, while StringBuilder is not
Explanation:
StringBuffer is thread-safe due to synchronized methods, making it slower than StringBuilder, which is not synchronized.

9. Which of the following accurately describes the double equals operator and the equals() method?

a) Both compare object memory addresses
b) Both compare object values
c) The operator compares values, while the method compares memory addresses
d) The operator compares memory addresses, while the method compares logical equivalence
Correct Answer: d) The operator compares memory addresses, while the method compares logical equivalence
Explanation:
The double equals operator checks for reference equality, while the equals() method checks for value equality.

10. Which of the following is true about abstract classes in Java?

a) They can be instantiated directly
b) They must contain at least one abstract method
c) They cannot have constructors
d) They can have both abstract and concrete methods
Correct Answer: d) They can have both abstract and concrete methods
Explanation:
Abstract classes cannot be instantiated, but they can have constructors and a mix of abstract and non-abstract methods.

11. Does Java support multiple inheritance?

a) Yes, through classes
b) Yes, through interfaces
c) No, not in any form
d) Yes, through abstract classes
Correct Answer: b) Yes, through interfaces
Explanation:
Java avoids the Diamond Problem by not allowing multiple inheritance of classes, but a class can implement multiple interfaces.

12. What is the purpose of the super keyword in Java?

a) To refer to the current object
b) To call static methods of the parent class
c) To refer to the immediate parent class object
d) To create a new instance of a class
Correct Answer: c) To refer to the immediate parent class object
Explanation:
The super keyword is a reference variable used to refer to immediate parent class objects, methods, or constructors.

13. What is method overloading?

a) Defining multiple methods with the same name but different parameters in the same class
b) Providing a specific implementation in a subclass for a method defined in the parent class
c) Defining a method with the same name in different classes
d) Hiding a parent class method by defining it as static in the subclass
Correct Answer: a) Defining multiple methods with the same name but different parameters in the same class
Explanation:
Method overloading is a compile-time polymorphism where methods have the same name but differ in type or number of arguments.

14. What is method overriding?

a) Defining multiple methods with the same name in the same class
b) Providing a specific implementation in a subclass for a method defined in its superclass
c) Changing the return type of a method in the subclass without changing parameters
d) Calling a method repeatedly in a loop
Correct Answer: b) Providing a specific implementation in a subclass for a method defined in its superclass
Explanation:
Method overriding is runtime polymorphism where a subclass provides its own implementation for an inherited method.

15. What is the primary use of the instanceof operator?

a) To create an instance of a class
b) To check if an object is an instance of a specific class or interface
c) To copy the properties of one instance to another
d) To delete an instance from memory
Correct Answer: b) To check if an object is an instance of a specific class or interface
Explanation:
The instanceof operator returns a boolean value indicating whether an object is of a particular class or interface type.

16. Which OOP concept is demonstrated by making fields private and providing public getter and setter methods?

a) Polymorphism
b) Inheritance
c) Encapsulation
d) Abstraction
Correct Answer: c) Encapsulation
Explanation:
Encapsulation is the mechanism of wrapping the data and code acting on the data together, hiding internal state.

17. What is Upcasting in Java?

a) Casting a superclass reference to a subclass type
b) Casting a subclass reference to a superclass type
c) Converting a string to an integer
d) Casting an interface to an abstract class
Correct Answer: b) Casting a subclass reference to a superclass type
Explanation:
Upcasting is assigning a child class object to a parent class reference variable. It is done implicitly in Java.

18. What is Downcasting in Java?

a) Casting a superclass reference to a subclass type
b) Casting a subclass reference to a superclass type
c) Removing inheritance from a class
d) Converting an integer to a byte
Correct Answer: a) Casting a superclass reference to a subclass type
Explanation:
Downcasting is explicitly casting a parent class reference back to a child class type.

19. Which of the following is a checked exception?

a) NullPointerException
b) ArithmeticException
c) IOException
d) ArrayIndexOutOfBoundsException
Correct Answer: c) IOException
Explanation:
Checked exceptions are checked at compile-time. IOException is checked, while the others are unchecked runtime exceptions.

20. What is the superclass of all Exceptions and Errors in Java?

a) Exception
b) RuntimeException
c) Throwable
d) Object
Correct Answer: c) Throwable
Explanation:
The Throwable class is the superclass of all errors and exceptions in the Java language.

21. What happens if a finally block is used without a catch block?

a) It causes a compile-time error
b) It is valid, and the finally block executes whether an exception occurs or not
c) It is valid, but the finally block only executes if no exception occurs
d) It causes a runtime exception
Correct Answer: b) It is valid, and the finally block executes whether an exception occurs or not
Explanation:
A try block can be followed by a finally block without a catch block. The finally block always executes.

22. What is the difference between throw and throws?

a) throw declares an exception, throws is used to throw one explicitly
b) throw handles an exception, throws ignores it
c) throw is used to explicitly throw an exception, throws is used in the method signature to declare exceptions
d) There is no difference
Correct Answer: c) throw is used to explicitly throw an exception, throws is used in the method signature to declare exceptions
Explanation:
throw is followed by an instance of an exception, whereas throws is followed by exception class names in the method declaration.

23. Which interface is the root of the Java Collections Framework hierarchy for collections?

a) List
b) Map
c) Collection
d) Iterable
Correct Answer: d) Iterable
Explanation:
The Iterable interface is the root interface for all collection classes. Collection extends Iterable.

24. Which collection class allows you to associate its elements with a key?

a) Set
b) List
c) Map
d) Queue
Correct Answer: c) Map
Explanation:
The Map interface represents a mapping between a key and a value. It does not extend the Collection interface.

25. What is the main difference between ArrayList and LinkedList?

a) ArrayList is synchronized; LinkedList is not
b) ArrayList uses a dynamic array; LinkedList uses a doubly linked list
c) ArrayList does not allow nulls; LinkedList does
d) ArrayList allows duplicates; LinkedList does not
Correct Answer: b) ArrayList uses a dynamic array; LinkedList uses a doubly linked list
Explanation:
ArrayList provides fast random access, while LinkedList provides faster insertions and deletions.

26. Which Set implementation maintains the insertion order of elements?

a) HashSet
b) TreeSet
c) LinkedHashSet
d) EnumSet
Correct Answer: c) LinkedHashSet
Explanation:
LinkedHashSet uses a hash table and a doubly-linked list to maintain the insertion order of its elements.

27. What is the difference between HashMap and Hashtable?

a) HashMap is synchronized, Hashtable is not
b) Hashtable allows null keys, HashMap does not
c) HashMap allows one null key and multiple null values, Hashtable does not allow nulls
d) There is no difference
Correct Answer: c) HashMap allows one null key and multiple null values, Hashtable does not allow nulls
Explanation:
HashMap is non-synchronized and permits nulls. Hashtable is a legacy class that is synchronized and strictly non-null.

28. What does a fail-fast iterator do?

a) It ignores any structural modifications to the collection during iteration
b) It iterates faster than a regular iterator
c) It throws ConcurrentModificationException if the collection is structurally modified during iteration
d) It only works with primitive types
Correct Answer: c) It throws ConcurrentModificationException if the collection is structurally modified during iteration
Explanation:
Fail-fast iterators immediately throw an exception to prevent non-deterministic behavior during concurrent modification.

29. Which interface allows bi-directional traversal in a List?

a) Iterator
b) ListIterator
c) Enumeration
d) Spliterator
Correct Answer: b) ListIterator
Explanation:
ListIterator extends Iterator and provides methods to traverse the list in both forward and backward directions.

30. What is the difference between Comparable and Comparator?

a) Comparable provides natural sorting, Comparator provides custom sorting
b) Comparator provides natural sorting, Comparable provides custom sorting
c) Comparable is located in java.util, Comparator is in java.lang
d) There is no difference between them
Correct Answer: a) Comparable provides natural sorting, Comparator provides custom sorting
Explanation:
Comparable modifies the class itself (compareTo) for natural order. Comparator is external (compare) for custom strategies.

31. How do you create a thread in Java?

a) By extending the Thread class or implementing the Runnable interface
b) Only by extending the Thread class
c) Only by implementing the Runnable interface
d) By extending the Runnable class
Correct Answer: a) By extending the Thread class or implementing the Runnable interface
Explanation:
Java provides two main ways to create a thread: extending the java.lang.Thread class or implementing java.lang.Runnable.

32. What happens if you call the run() method directly instead of start()?

a) A new thread is created and executed
b) A runtime exception is thrown
c) The code inside run() executes in the current thread instead of a new thread
d) The application crashes
Correct Answer: c) The code inside run() executes in the current thread instead of a new thread
Explanation:
Calling run() does not create a new thread call stack. It executes sequentially in the current thread.

33. Which method releases the monitor lock on an object?

a) sleep()
b) yield()
c) wait()
d) join()
Correct Answer: c) wait()
Explanation:
The wait() method causes the current thread to wait and releases the lock it holds on the object.

34. What is a deadlock in Java?

a) When a thread completely stops running due to an error
b) When an exception terminates all threads
c) When two or more threads are blocked forever, waiting for each other to release a lock
d) When garbage collection pauses application threads
Correct Answer: c) When two or more threads are blocked forever, waiting for each other to release a lock
Explanation:
Deadlock is a concurrency failure mode where threads wait indefinitely for locks held by one another.

35. What is the purpose of the volatile keyword?

a) To mark a variable as a constant
b) To ensure visibility of a variable updates across different threads
c) To prevent a class from being inherited
d) To make a method thread-safe automatically
Correct Answer: b) To ensure visibility of a variable updates across different threads
Explanation:
The volatile keyword ensures that reads and writes to a variable go directly to main memory, preventing thread caching issues.

36. Which of the following is true about the Callable interface?

a) It cannot return a result
b) It cannot throw checked exceptions
c) It is part of the java.lang package
d) It returns a result and can throw checked exceptions
Correct Answer: d) It returns a result and can throw checked exceptions
Explanation:
Unlike Runnable, Callable's call() method can return a value (wrapped in a Future) and throw checked exceptions.

37. What is the role of ExecutorService in Java?

a) To manually start and join threads
b) To manage a pool of threads and abstract thread execution
c) To perform garbage collection
d) To serialize objects
Correct Answer: b) To manage a pool of threads and abstract thread execution
Explanation:
ExecutorService provides a higher-level framework for managing and pooling threads, simplifying concurrent task execution.

38. Who calls the finalize() method in Java?

a) The programmer
b) The operating system
c) The Garbage Collector
d) The main method
Correct Answer: c) The Garbage Collector
Explanation:
The finalize() method is called by the Garbage Collector just before reclaiming the object's memory.

39. What does System.gc() do?

a) It instantly forces garbage collection
b) It sends a request to the JVM to run the Garbage Collector
c) It clears the application cache
d) It stops all running threads
Correct Answer: b) It sends a request to the JVM to run the Garbage Collector
Explanation:
System.gc() is only a hint to the JVM. The JVM ultimately decides when to perform garbage collection.

40. What is a Marker Interface in Java?

a) An interface with exactly one method
b) An interface with only constant variables
c) An interface with no methods or constants, used to signal a property to the JVM
d) An interface that marks errors
Correct Answer: c) An interface with no methods or constants, used to signal a property to the JVM
Explanation:
Marker interfaces like Serializable contain no methods and instruct the JVM to treat the implementing class in a special way.

41. What is the purpose of the transient keyword?

a) To make a variable accessible by all threads
b) To prevent a variable from being serialized
c) To keep an object in memory permanently
d) To denote a variable that changes frequently
Correct Answer: b) To prevent a variable from being serialized
Explanation:
When an object is serialized, any field marked as transient is ignored and will not be saved.

42. What is Type Erasure in Java Generics?

a) The deletion of unused generic classes
b) The process where the compiler removes generic type information to ensure backward compatibility
c) A runtime exception when casting fails
d) The process of explicitly casting generic types
Correct Answer: b) The process where the compiler removes generic type information to ensure backward compatibility
Explanation:
Type erasure removes generic type bounds at compile time, replacing them with Object or bounds.

43. What does the wildcard question mark represent in Java generics?

a) A known primitive type
b) Any object type (unknown type)
c) A syntax error
d) The Object class strictly
Correct Answer: b) Any object type (unknown type)
Explanation:
The question mark represents an unknown type in generic programming, often used as bounded wildcards.

44. Which class is the superclass for all enum types in Java?

a) java.lang.Class
b) java.lang.Enum
c) java.util.EnumSet
d) java.lang.Object (directly)
Correct Answer: b) java.lang.Enum
Explanation:
Every enum type implicitly extends java.lang.Enum, meaning enums cannot extend other classes.

45. What is an annotation in Java?

a) A type of comment that the compiler ignores entirely
b) A tag providing metadata about the program that is not part of the program itself
c) A method that runs before the constructor
d) A special class for logging
Correct Answer: b) A tag providing metadata about the program that is not part of the program itself
Explanation:
Annotations provide data about a program to the compiler, deployment tools, or runtime environments.

46. What is a Functional Interface in Java?

a) An interface with no abstract methods
b) An interface with exactly one abstract method
c) An interface that provides utility functions
d) An interface that has only default methods
Correct Answer: b) An interface with exactly one abstract method
Explanation:
Functional interfaces have a single abstract method and can be implemented using lambda expressions.

47. What is a Lambda Expression in Java 8?

a) A tool to compile Java code faster
b) An anonymous function that can be created without belonging to any class
c) A mathematical library
d) A new primitive data type
Correct Answer: b) An anonymous function that can be created without belonging to any class
Explanation:
Lambda expressions provide a clear and concise way to represent one-method interfaces using an expression.

48. Which annotation guarantees that an interface meets the requirements of a functional interface?

a) @Function
b) @Functional
c) @FunctionalInterface
d) @Lambda
Correct Answer: c) @FunctionalInterface
Explanation:
The @FunctionalInterface annotation informs the compiler to check that the interface contains exactly one abstract method.

49. What is the primary purpose of the Stream API in Java 8?

a) To read and write files asynchronously
b) To process collections of objects in a functional and declarative style
c) To stream video over HTTP
d) To replace the Collections framework completely
Correct Answer: b) To process collections of objects in a functional and declarative style
Explanation:
Streams provide a high-level abstraction for processing sequences of data using operations like map, filter, and reduce.

50. Which of the following is a terminal operation in the Stream API?

a) filter()
b) map()
c) collect()
d) peek()
Correct Answer: c) collect()
Explanation:
collect() is a terminal operation that triggers the execution of the stream pipeline and returns a result.

51. What is the difference between map() and flatMap() in Streams?

a) map() transforms values, flatMap() transforms and flattens nested streams
b) map() flattens streams, flatMap() transforms values
c) There is no difference
d) map() is terminal, flatMap() is intermediate
Correct Answer: a) map() transforms values, flatMap() transforms and flattens nested streams
Explanation:
map() applies a function to each element. flatMap() applies a function that returns a stream, and then flattens those into one.

52. What is the purpose of the Optional class introduced in Java 8?

a) To optionally compile code
b) To act as a container object for values that may or may not be present, avoiding NullPointerExceptions
c) To make variables optional in method signatures
d) To represent multiple return types
Correct Answer: b) To act as a container object for values that may or may not be present, avoiding NullPointerExceptions
Explanation:
Optional is a value-based class that forces developers to explicitly handle the case where a value might be null.

53. Which operator is used for Method References in Java 8?

a) ->
b) ::
c) =>
d) :-
Correct Answer: b) ::
Explanation:
The double colon operator is the method reference operator, used to refer to a method without invoking it.

54. Why were default methods introduced in interfaces in Java 8?

a) To allow interfaces to have constructors
b) To enforce multiple inheritance of state
c) To allow adding new methods to interfaces without breaking existing implementations
d) To replace abstract classes
Correct Answer: c) To allow adding new methods to interfaces without breaking existing implementations
Explanation:
Default methods provide backward compatibility, allowing developers to add new methods to interfaces safely.

55. Can an interface have static methods in Java 8?

a) No, interfaces can only have abstract methods
b) Yes, but they cannot have a body
c) Yes, and they are used to provide utility methods relevant to the interface
d) Only functional interfaces can have static methods
Correct Answer: c) Yes, and they are used to provide utility methods relevant to the interface
Explanation:
Java 8 introduced static methods in interfaces with implementations, primarily used as utility or helper methods.

56. Which package was introduced in Java 8 to replace the flawed java.util.Date and Calendar?

a) java.datetime
b) java.time
c) java.util.date
d) java.joda
Correct Answer: b) java.time
Explanation:
The java.time package provides a new, immutable, thread-safe Date and Time API.

57. What is Autoboxing in Java?

a) Automatic conversion of objects into primitive types
b) Automatic conversion of primitive types into their corresponding wrapper class objects
c) Automatic garbage collection of boxed types
d) Implicitly casting child class to parent class
Correct Answer: b) Automatic conversion of primitive types into their corresponding wrapper class objects
Explanation:
Autoboxing converts primitive types into their wrapper classes automatically (e.g., int to Integer).

58. Is Java Pass-by-Value or Pass-by-Reference?

a) Pass-by-Reference strictly
b) Pass-by-Value for primitives, Pass-by-Reference for objects
c) Pass-by-Value strictly
d) Depends on the JVM
Correct Answer: c) Pass-by-Value strictly
Explanation:
Java is strictly pass-by-value. For objects, the value passed is a copy of the reference to the memory location.

59. Which memory area does an OutOfMemoryError typically point to?

a) The Call Stack
b) The Heap Space
c) The Register
d) The Program Counter
Correct Answer: b) The Heap Space
Explanation:
Objects are allocated in the Heap. An OutOfMemoryError usually means the heap is full.

60. What usually causes a StackOverflowError?

a) Creating too many objects
b) Infinite or overly deep recursive method calls
c) Loading too many classes
d) Accessing an array out of bounds
Correct Answer: b) Infinite or overly deep recursive method calls
Explanation:
Each method call creates a new frame on the stack. Deep or infinite recursion exhausts the stack space.

61. What is the difference between ClassNotFoundException and NoClassDefFoundError?

a) They are exactly the same
b) ClassNotFoundException occurs during explicit loading, while NoClassDefFoundError occurs during implicit linking at runtime
c) ClassNotFoundException is an error, while NoClassDefFoundError is a checked exception
d) NoClassDefFoundError occurs at compile-time
Correct Answer: b) ClassNotFoundException occurs during explicit loading, while NoClassDefFoundError occurs during implicit linking at runtime
Explanation:
ClassNotFoundException happens during reflection (Class.forName). NoClassDefFoundError is thrown by the JVM when a linked class is missing.

62. Which of the following is NOT a built-in ClassLoader in Java?

a) Bootstrap ClassLoader
b) Extension ClassLoader
c) System/Application ClassLoader
d) Dynamic ClassLoader
Correct Answer: d) Dynamic ClassLoader
Explanation:
The three standard class loaders in Java are Bootstrap, Extension, and System ClassLoaders.

63. What is the primary characteristic of the Singleton Design Pattern?

a) It allows only a single instance of a class to be created per JVM
b) It provides a single interface for a complex subsystem
c) It allows a single thread to execute
d) It hides the instantiation process
Correct Answer: a) It allows only a single instance of a class to be created per JVM
Explanation:
Singleton ensures that a class has only one instance and provides a global point of access to it.

64. Which design pattern is used to create objects without exposing the instantiation logic to the client?

a) Singleton
b) Observer
c) Factory
d) Decorator
Correct Answer: c) Factory
Explanation:
The Factory design pattern provides an interface for creating objects in a superclass, deferring instantiation to subclasses.

65. Where are local variables and method parameters stored in Java memory?

a) Heap
b) Metaspace
c) Stack
d) Constant Pool
Correct Answer: c) Stack
Explanation:
Thread-specific data like local variables, method parameters, and return addresses are stored on the Stack.

66. What replaced the PermGen space in Java 8?

a) Tenured Generation
b) Survivor Space
c) Metaspace
d) Eden Space
Correct Answer: c) Metaspace
Explanation:
Java 8 removed the Permanent Generation (PermGen) and replaced it with Metaspace, which dynamically allocates from native memory.

67. Is StringBuilder thread-safe?

a) Yes, all its methods are synchronized
b) No, it is not synchronized and therefore not thread-safe
c) Yes, because it is immutable
d) No, because it does not implement Serializable
Correct Answer: b) No, it is not synchronized and therefore not thread-safe
Explanation:
StringBuilder was introduced as a non-synchronized, faster drop-in replacement for StringBuffer in single-threaded scenarios.

68. How do you define a method that takes a variable number of arguments (varargs) in Java?

a) public void printArgs(String... args)
b) public void printArgs(String[]... args)
c) public void printArgs(...String args)
d) public void printArgs(String args...)
Correct Answer: a) public void printArgs(String... args)
Explanation:
Varargs are specified by three dots after the type. They must be the last parameter in the method signature.

69. Which of the following data types cannot be used in a switch statement prior to Java 12?

a) String
b) int
c) long
d) enum
Correct Answer: c) long
Explanation:
A switch statement in classic Java supports byte, short, char, int, enum, and String, but does not support long, float, double, or boolean.

70. What does the continue statement do inside a loop?

a) Exits the loop entirely
b) Returns a value from the loop
c) Skips the current iteration and jumps to the next iteration
d) Pauses the loop execution
Correct Answer: c) Skips the current iteration and jumps to the next iteration
Explanation:
The continue statement bypasses the rest of the code in the current loop iteration and proceeds to the next evaluation.

71. What is a labeled break in Java?

a) A break that prints a message to the console
b) A break statement that terminates a specific labeled loop in nested loops
c) A break that throws an exception
d) There is no labeled break in Java
Correct Answer: b) A break statement that terminates a specific labeled loop in nested loops
Explanation:
A labeled break allows breaking out of an outer loop from within a nested inner loop by referencing a label.

72. What is the size of the int data type in Java?

a) 16 bits
b) 32 bits
c) 64 bits
d) Depends on the operating system
Correct Answer: b) 32 bits
Explanation:
In Java, an int is always a 32-bit signed two-s complement integer, regardless of the underlying platform.

73. What is the size of a double data type compared to a float?

a) Double is 32 bits, float is 64 bits
b) Double is 64 bits, float is 32 bits
c) Both are 64 bits
d) Both are 32 bits
Correct Answer: b) Double is 64 bits, float is 32 bits
Explanation:
A float is a single-precision 32-bit floating point, whereas a double is a double-precision 64-bit floating point.

74. Which method is used to create a copy of an object?

a) copy()
b) duplicate()
c) clone()
d) replicate()
Correct Answer: c) clone()
Explanation:
The clone() method from the Object class is used to create a copy of the object, provided the class implements Cloneable.

75. What is the difference between a shallow copy and a deep copy?

a) Shallow copy copies references, deep copy copies actual objects
b) Shallow copy copies actual objects, deep copy copies references
c) There is no difference
d) Shallow copy is used for primitives, deep copy for objects
Correct Answer: a) Shallow copy copies references, deep copy copies actual objects
Explanation:
In a shallow copy, nested objects share the same memory reference. In a deep copy, completely independent copies are created.

76. Which class provides utility methods for mathematical operations like min, max, and sqrt?

a) java.lang.Math
b) java.util.Math
c) java.lang.Number
d) java.math.BigDecimal
Correct Answer: a) java.lang.Math
Explanation:
The java.lang.Math class contains static methods for performing basic numeric operations.

77. Which method in the Math class returns a random number between 0.0 and 1.0?

a) Math.random()
b) Math.getRandom()
c) Math.rand()
d) Math.generate()
Correct Answer: a) Math.random()
Explanation:
Math.random() returns a double value greater than or equal to 0.0 and less than 1.0.

78. What is a Record in Java 14+?

a) A new database connectivity class
b) A compact syntax for declaring data-carrying classes with immutable state
c) An interface for logging application events
d) A substitute for traditional arrays
Correct Answer: b) A compact syntax for declaring data-carrying classes with immutable state
Explanation:
Records provide a concise way to create immutable data carriers, automatically generating getters, constructors, equals, and hashCode.

79. What does the var keyword do in Java 10+?

a) It allows declaring variables without static typing
b) It turns Java into a dynamically typed language
c) It allows local variable type inference where the compiler deduces the type
d) It allows changing the variable type at runtime
Correct Answer: c) It allows local variable type inference where the compiler deduces the type
Explanation:
The var keyword allows the compiler to infer the type of a local variable from its initializer, keeping Java statically typed.

80. How are threads typically executed when using an ExecutorService?

a) They execute immediately blocking the main thread
b) They are submitted as tasks using methods like execute() or submit()
c) They require the manual invocation of the start() method
d) They can only run sequentially
Correct Answer: b) They are submitted as tasks using methods like execute() or submit()
Explanation:
With an ExecutorService, tasks are submitted via execute() or submit(), and the framework handles thread assignment.

81. What does the ThreadLocal class provide in Java?

a) Thread safety by synchronizing objects
b) A mechanism to run threads sequentially
c) Variables that are local and independent to the specific thread that accesses them
d) A localized geographical thread priority
Correct Answer: c) Variables that are local and independent to the specific thread that accesses them
Explanation:
ThreadLocal allows you to store variables that are only accessible to the specific thread that reads or writes them.

82. What is the primary difference between an Array and an ArrayList in Java?

a) Array is dynamic in size, ArrayList is fixed
b) Array can hold primitives, ArrayList can only hold Objects
c) Array is part of the Collections framework, ArrayList is not
d) There is no difference
Correct Answer: b) Array can hold primitives, ArrayList can only hold Objects
Explanation:
Arrays have a fixed size and can hold primitives. ArrayList has a dynamic size and stores only objects.

83. What sorting algorithm does Collections.sort() use under the hood for objects in modern Java?

a) Bubble Sort
b) Quick Sort
c) TimSort (a hybrid of Merge Sort and Insertion Sort)
d) Heap Sort
Correct Answer: c) TimSort (a hybrid of Merge Sort and Insertion Sort)
Explanation:
Since Java 7, object arrays and collections are sorted using TimSort, which is stable and highly optimized.

84. What is the Big-O time complexity of retrieving an element by key in a HashMap under average conditions?

a) O(n)
b) O(log n)
c) O(1)
d) O(n^2)
Correct Answer: c) O(1)
Explanation:
Assuming a good hash function with minimal collisions, a HashMap provides constant time O(1) for get and put operations.

85. What does the keyword strictfp do?

a) Enforces strict access control
b) Ensures that floating-point calculations result in the exact same values across all platforms
c) Prevents file parsing errors
d) Makes methods run faster
Correct Answer: b) Ensures that floating-point calculations result in the exact same values across all platforms
Explanation:
The strictfp keyword restricts floating-point calculations to ensure portability across different hardware architectures.

86. Which block is executed when an exception occurs in a try block?

a) try
b) catch
c) finally
d) throw
Correct Answer: b) catch
Explanation:
The catch block handles the exception that is thrown by the code within the try block.

87. Can we have multiple catch blocks for a single try block?

a) Yes, but they must be ordered from most general to most specific exception
b) Yes, but they must be ordered from most specific to most general exception
c) No, only one catch block is allowed
d) Yes, but only if they catch the exact same exception
Correct Answer: b) Yes, but they must be ordered from most specific to most general exception
Explanation:
If a general exception is placed before a specific one, the compiler throws an unreachable code error.

88. What is a native method in Java?

a) A method written in Java but optimized by the JVM
b) A method written in another language and executed outside the JVM
c) A method that relies strictly on native Java libraries
d) A method without a return type
Correct Answer: b) A method written in another language and executed outside the JVM
Explanation:
The native keyword allows Java code to call functions written in languages like C or C++ via JNI.

89. What does the readLine() method of BufferedReader return when the end of the stream is reached?

a) An empty string
b) null
c) The number -1
d) It throws an EOFException
Correct Answer: b) null
Explanation:
BufferedReader.readLine() returns a String containing the line, or null if the end of the stream is reached.

90. Which statement about Constructors is false?

a) They must have the same name as the class
b) They cannot have a return type
c) They can be inherited by subclasses
d) They can be overloaded
Correct Answer: c) They can be inherited by subclasses
Explanation:
Constructors are not inherited by subclasses. A subclass must call the superclass constructor explicitly or implicitly.

91. What does the access modifier protected imply?

a) Accessible anywhere in the program
b) Accessible only within the same class
c) Accessible within the same package and by subclasses in other packages
d) Accessible only within the same package
Correct Answer: c) Accessible within the same package and by subclasses in other packages
Explanation:
The protected modifier grants access to classes within the same package and to any subclass globally.

92. What is an Anonymous Inner Class?

a) An inner class that has no name and is instantiated in a single expression
b) A class defined outside any package
c) An interface that cannot be implemented
d) A class that hides its members completely
Correct Answer: a) An inner class that has no name and is instantiated in a single expression
Explanation:
Anonymous classes enable you to declare and instantiate a class simultaneously, often used for listeners.

93. Which design pattern restricts object creation for a class to only one instance?

a) Prototype Pattern
b) Builder Pattern
c) Singleton Pattern
d) Adapter Pattern
Correct Answer: c) Singleton Pattern
Explanation:
The Singleton pattern ensures that a class has only one instance and provides a global access point.

94. Which collection class represents a FIFO (First-In-First-Out) queue by default?

a) Stack
b) LinkedList
c) Vector
d) TreeSet
Correct Answer: b) LinkedList
Explanation:
LinkedList implements the Queue and Deque interfaces, making it capable of acting as a FIFO queue.

95. What is the return type of the wait() method?

a) int
b) void
c) boolean
d) Object
Correct Answer: b) void
Explanation:
The wait() method, located in the Object class, pauses the thread and returns void.

96. How do you synchronize an entire method in Java?

a) By using the synchronized keyword in the method signature
b) By using a Lock object strictly
c) By using the volatile keyword
d) By extending the Synchronize class
Correct Answer: a) By using the synchronized keyword in the method signature
Explanation:
Placing the synchronized keyword in a method declaration locks the intrinsic monitor of the object or class.

97. What happens when a thread is interrupted while sleeping?

a) It silently wakes up and continues execution
b) It throws an InterruptedException
c) The application crashes
d) It stops running completely
Correct Answer: b) It throws an InterruptedException
Explanation:
If any thread interrupts a sleeping thread, the sleeping thread will wake up and throw an InterruptedException.

98. What is a memory leak in Java?

a) When the JVM crashes unexpectedly
b) When memory is physically damaged
c) When objects are no longer needed but are still referenced, preventing garbage collection
d) When variables are declared without initialization
Correct Answer: c) When objects are no longer needed but are still referenced, preventing garbage collection
Explanation:
A memory leak happens when an application inadvertently holds onto object references that are no longer needed.

99. Which Garbage Collector is the default in Java 11?

a) Serial GC
b) Parallel GC
c) G1 GC (Garbage-First Collector)
d) ZGC (Z Garbage Collector)
Correct Answer: c) G1 GC (Garbage-First Collector)
Explanation:
Starting from Java 9, G1 GC is the default garbage collector, optimized for multi-processor machines with large memories.

100. What is Covariant Return Type in Java?

a) Returning two values from a method
b) An overridden method returning a subclass of the type returned by the original method
c) A method that returns varying primitive types
d) A generic type return
Correct Answer: b) An overridden method returning a subclass of the type returned by the original method
Explanation:
Java allows an overriding method to return a more specific subclass type than the overridden method.

101. What does the String.intern() method do?

a) It reverses the string
b) It returns a canonical representation for the string object from the string pool
c) It converts the string to uppercase
d) It encrypts the string
Correct Answer: b) It returns a canonical representation for the string object from the string pool
Explanation:
Calling intern() checks if the string exists in the String pool and returns it, or adds it to the pool if it does not exist.

102. What is the difference between an inner class and a subclass?

a) An inner class inherits from another class, a subclass is nested inside another class
b) An inner class is nested inside another class, a subclass inherits from another class
c) They are exactly the same concept
d) An inner class can be instantiated independently, a subclass cannot
Correct Answer: b) An inner class is nested inside another class, a subclass inherits from another class
Explanation:
Inner classes deal with scope and containment, whereas subclasses deal with inheritance.

103. Can we execute a Java program without the main method in modern Java (Java 7+)?

a) Yes, always
b) No, it is strictly required by the JVM to launch the application
c) Yes, using static blocks alone
d) Yes, using the finalize method
Correct Answer: b) No, it is strictly required by the JVM to launch the application
Explanation:
Since Java 7, the JVM explicitly checks for the main method before executing any static blocks.

104. What is Dependency Injection (DI) commonly used for in frameworks like Spring?

a) To inject malicious code
b) To manage object creation and the binding of dependencies externally
c) To connect to databases exclusively
d) To inject CSS into HTML
Correct Answer: b) To manage object creation and the binding of dependencies externally
Explanation:
DI delegates the responsibility of instantiating dependencies to an external framework, promoting loose coupling.

105. What is the Java Reflection API used for?

a) To reflect output on the console
b) To inspect or modify the runtime behavior of applications and dynamically invoke methods
c) To map objects to database tables
d) To duplicate classes in memory
Correct Answer: b) To inspect or modify the runtime behavior of applications and dynamically invoke methods
Explanation:
Reflection allows introspection of classes, interfaces, fields, and methods at runtime.

106. Which keyword is used to establish an IS-A relationship?

a) implements
b) extends
c) new
d) instanceof
Correct Answer: b) extends
Explanation:
The extends keyword establishes class inheritance, creating an IS-A relationship.

107. What does a java.lang.NullPointerException imply?

a) An uninitialized integer is used in a calculation
b) The application attempted to use an object reference that has the null value
c) A string could not be parsed into a number
d) An array index was out of bounds
Correct Answer: b) The application attempted to use an object reference that has the null value
Explanation:
Calling instance methods or accessing fields on a variable pointing to null triggers this unchecked exception.

108. What does the Collection.removeIf() method do?

a) Removes the first element if it exists
b) Removes all elements of the collection that satisfy the given predicate
c) Removes duplicate elements
d) Removes an element safely during normal iteration without an explicit iterator
Correct Answer: b) Removes all elements of the collection that satisfy the given predicate
Explanation:
removeIf() takes a Predicate and safely removes all items matching the condition.

109. Which class represents an immutable sequence of characters?

a) StringBuilder
b) StringBuffer
c) String
d) Character
Correct Answer: c) String
Explanation:
String objects in Java are immutable; their internal state cannot be changed after creation.

110. How can you prevent a method from being overridden?

a) Declare it as private
b) Declare it as final
c) Declare it as static
d) All of the above
Correct Answer: d) All of the above
Explanation:
Private and static methods belong to the class and are hidden, while final explicitly locks a method against overriding.

111. What happens when you compile a Java program?

a) It creates an executable file
b) It produces bytecode stored in a class file
c) It translates the code into assembly language
d) It runs the program immediately
Correct Answer: b) It produces bytecode stored in a class file
Explanation:
The Java compiler (javac) converts source files into .class bytecode files that the JVM can interpret.

112. What is the difference between Array and LinkedList traversal performance?

a) Arrays provide O(1) random access, LinkedLists require O(n) traversal
b) LinkedLists provide O(1) random access, Arrays require O(n) traversal
c) Both require O(n) traversal
d) Both provide O(1) traversal
Correct Answer: a) Arrays provide O(1) random access, LinkedLists require O(n) traversal
Explanation:
Arrays allocate continuous memory allowing direct O(1) index access, whereas LinkedLists require sequential node traversal.
← Previous: Java Interfaces and Abstract Classes MCQs
Next →: Java Multithreading & Concurrency MCQs
Python Functions MCQs

Python Functions MCQs

Functions in Python are reusable blocks of code designed to perform a specific task, promoting code modularity, readability, and DRY…

By MCQs Generator
important java 8 features mcqs

Important Java 8 Features MCQs

Released in March 2014, Java 8 represents one of the most significant upgrades in the history of the Java programming…

By MCQs Generator
Latest Python Dictionaries MCQs

Latest Python Dictionaries MCQs

Python dictionaries are built-in data structures used to store data in key-value pairs, providing fast lookups, insertions, and deletions. Keys…

By MCQs Generator