Multiple Choice Questions

Test your Java knowledge with unit-wise MCQs

Unit I: Java Fundamentals

1. Which component is responsible for converting bytecode to machine code?

  • a) JDK
  • b) JRE
  • c) JVM
  • d) Compiler
Show Answer

c) JVM - The Java Virtual Machine interprets/compiles bytecode to machine code at runtime.

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

  • a) 2 bytes
  • b) 4 bytes
  • c) 8 bytes
  • d) Depends on platform
Show Answer

b) 4 bytes - int is always 32 bits (4 bytes) in Java regardless of platform.

3. Which keyword is used to prevent method overriding?

  • a) static
  • b) final
  • c) abstract
  • d) const
Show Answer

b) final - A final method cannot be overridden in subclasses.

4. What is the default value of a boolean instance variable?

  • a) true
  • b) false
  • c) null
  • d) 0
Show Answer

b) false - Boolean instance variables default to false.

5. Which operator is used to check if an object is an instance of a class?

  • a) typeof
  • b) instanceof
  • c) isInstance
  • d) classof
Show Answer

b) instanceof - The instanceof operator checks object type at runtime.

6. Which access modifier makes a member visible only within the same package?

  • a) private
  • b) protected
  • c) default (no modifier)
  • d) public
Show Answer

c) default - Package-private access when no modifier is specified.

7. What is the output of: System.out.println(10 + 20 + "Hello");

  • a) 1020Hello
  • b) 30Hello
  • c) Hello1020
  • d) Hello30
Show Answer

b) 30Hello - Left to right: 10+20=30, then 30+"Hello"="30Hello".

8. Which method is used to compare string contents?

  • a) ==
  • b) compare()
  • c) equals()
  • d) match()
Show Answer

c) equals() - The equals() method compares string content; == compares references.

9. Which class is mutable and thread-safe for string operations?

  • a) String
  • b) StringBuilder
  • c) StringBuffer
  • d) StringWriter
Show Answer

c) StringBuffer - StringBuffer is mutable and synchronized (thread-safe).

10. What is method overloading?

  • a) Same method name, same parameters in subclass
  • b) Same method name, different parameters in same class
  • c) Different method name, same parameters
  • d) Override parent method
Show Answer

b) Same method name, different parameters in same class - Compile-time polymorphism.

11. Which loop is guaranteed to execute at least once?

  • a) for
  • b) while
  • c) do-while
  • d) for-each
Show Answer

c) do-while - Condition is checked after the loop body executes.

12. How many objects can a Java class extend?

  • a) 0
  • b) 1
  • c) 2
  • d) Unlimited
Show Answer

b) 1 - Java supports single inheritance for classes.

13. What does JDK stand for?

  • a) Java Development Kit
  • b) Java Deployment Kit
  • c) Java Debug Kit
  • d) Java Design Kit
Show Answer

a) Java Development Kit - Contains JRE + development tools (compiler, debugger).

14. Which keyword is used to create a constant in Java?

  • a) const
  • b) final
  • c) static
  • d) constant
Show Answer

b) final - final variables cannot be reassigned. const is reserved but not used.

15. What is the index of the first element in an array?

  • a) -1
  • b) 0
  • c) 1
  • d) Depends on declaration
Show Answer

b) 0 - Java arrays are zero-indexed.

16. What is the output of: int x = 5; System.out.println(x++ + ++x);

  • a) 10
  • b) 11
  • c) 12
  • d) 13
Show Answer

c) 12 - x++ returns 5 (then x=6), ++x returns 7 (x=7). 5+7=12.

17. Which method must be defined in every Java application?

  • a) start()
  • b) main()
  • c) run()
  • d) init()
Show Answer

b) main() - public static void main(String[] args) is the entry point.

18. What is the size of char data type in Java?

  • a) 1 byte
  • b) 2 bytes
  • c) 4 bytes
  • d) 8 bytes
Show Answer

b) 2 bytes - char uses Unicode and is 16 bits (2 bytes).

19. Which of these is NOT a valid primitive data type?

  • a) int
  • b) boolean
  • c) String
  • d) double
Show Answer

c) String - String is a class (reference type), not a primitive.

20. What does the 'static' keyword mean when applied to a method?

  • a) The method can be called without creating an object
  • b) The method cannot be overridden
  • c) The method is synchronized
  • d) The method is abstract
Show Answer

a) The method can be called without creating an object - Static methods belong to the class, not instances.

21. What is the difference between '==' and '.equals()' for Strings?

  • a) They are the same
  • b) == compares references, equals() compares content
  • c) == compares content, equals() compares references
  • d) Neither can compare Strings
Show Answer

b) == compares references, equals() compares content - Always use equals() for string comparison.

22. Which loop is guaranteed to execute at least once?

  • a) for loop
  • b) while loop
  • c) do-while loop
  • d) enhanced for loop
Show Answer

c) do-while loop - Checks condition after execution, so runs at least once.

23. What is the output of: System.out.println(10 / 3);

  • a) 3
  • b) 3.0
  • c) 3.33
  • d) 3.3333333
Show Answer

a) 3 - Integer division truncates the decimal part.

24. Which keyword is used to inherit a class?

  • a) implements
  • b) extends
  • c) inherits
  • d) super
Show Answer

b) extends - Used for class inheritance (implements is for interfaces).

25. What is encapsulation?

  • a) Hiding implementation details
  • b) Wrapping data and methods in a single unit
  • c) Using private access modifiers
  • d) All of the above
Show Answer

d) All of the above - Encapsulation involves bundling data with methods and restricting direct access.

Unit II: Exception Handling, I/O, Multithreading

1. Which is the parent class of all exceptions?

  • a) Exception
  • b) Error
  • c) Throwable
  • d) RuntimeException
Show Answer

c) Throwable - Both Exception and Error extend Throwable.

2. Which block always executes regardless of exception?

  • a) try
  • b) catch
  • c) finally
  • d) throw
Show Answer

c) finally - Executes even if exception occurs (except System.exit()).

3. Which keyword is used to declare that a method may throw an exception?

  • a) throw
  • b) throws
  • c) try
  • d) catch
Show Answer

b) throws - Used in method signature; throw is used to actually throw an exception.

4. Which exception is checked at compile time?

  • a) NullPointerException
  • b) ArrayIndexOutOfBoundsException
  • c) IOException
  • d) ArithmeticException
Show Answer

c) IOException - Checked exceptions must be handled or declared.

5. Which stream is used to read bytes from a file?

  • a) FileReader
  • b) FileInputStream
  • c) BufferedReader
  • d) Scanner
Show Answer

b) FileInputStream - Byte stream for reading files; FileReader is for characters.

6. Which method is used to start a thread?

  • a) run()
  • b) start()
  • c) execute()
  • d) begin()
Show Answer

b) start() - Calling run() directly doesn't create a new thread.

7. Which interface must be implemented to create a thread?

  • a) Executable
  • b) Runnable
  • c) Threadable
  • d) Running
Show Answer

b) Runnable - Contains single run() method; alternative to extending Thread.

8. What is the default priority of a thread?

  • a) 1
  • b) 5
  • c) 10
  • d) 0
Show Answer

b) 5 - Thread.NORM_PRIORITY = 5 (range is 1-10).

9. Which keyword is used to prevent race conditions?

  • a) volatile
  • b) synchronized
  • c) atomic
  • d) locked
Show Answer

b) synchronized - Ensures only one thread accesses critical section at a time.

10. Which method releases the lock and waits?

  • a) sleep()
  • b) wait()
  • c) yield()
  • d) join()
Show Answer

b) wait() - Releases lock and waits; sleep() doesn't release lock.

11. Which class is used for buffered character reading?

  • a) BufferedInputStream
  • b) BufferedReader
  • c) DataInputStream
  • d) FileReader
Show Answer

b) BufferedReader - Character stream with buffering; provides readLine().

12. What happens if you call run() instead of start()?

  • a) New thread is created
  • b) Method runs in current thread
  • c) Compilation error
  • d) Runtime error
Show Answer

b) Method runs in current thread - No new thread is spawned.

13. Which method wakes up all waiting threads?

  • a) notify()
  • b) notifyAll()
  • c) wakeAll()
  • d) resume()
Show Answer

b) notifyAll() - Wakes all threads; notify() wakes only one.

14. try-with-resources requires resources to implement which interface?

  • a) Closeable
  • b) AutoCloseable
  • c) Disposable
  • d) Both a and b
Show Answer

d) Both a and b - Closeable extends AutoCloseable; both work.

15. Which thread state means the thread is waiting for a lock?

  • a) RUNNABLE
  • b) BLOCKED
  • c) WAITING
  • d) TIMED_WAITING
Show Answer

b) BLOCKED - Waiting to acquire a monitor lock.

16. What type of exception is NullPointerException?

  • a) Checked exception
  • b) Unchecked exception
  • c) Compile-time exception
  • d) IO exception
Show Answer

b) Unchecked exception - Extends RuntimeException.

17. Can a method declare multiple exceptions in throws clause?

  • a) No, only one allowed
  • b) Yes, separated by commas
  • c) Yes, separated by semicolons
  • d) Only if they are related
Show Answer

b) Yes, separated by commas - public void method() throws IOException, SQLException

18. What happens if finally block throws an exception?

  • a) Both exceptions are thrown
  • b) Finally block exception is thrown, try/catch exceptions are lost
  • c) Compilation error
  • d) Finally block exception is ignored
Show Answer

b) Finally block exception is thrown, try/catch exceptions are lost - Finally block exception overrides.

19. Which exception occurs when parsing invalid string to number?

  • a) NumberException
  • b) ParseException
  • c) NumberFormatException
  • d) InvalidNumberException
Show Answer

c) NumberFormatException - When Integer.parseInt("abc") fails.

20. What is the difference between FileInputStream and FileReader?

  • a) No difference
  • b) FileInputStream for bytes, FileReader for characters
  • c) FileInputStream for text, FileReader for binary
  • d) FileInputStream is deprecated
Show Answer

b) FileInputStream for bytes, FileReader for characters - Byte stream vs Character stream.

Unit III: Modern Java Features

1. How many abstract methods can a functional interface have?

  • a) 0
  • b) 1
  • c) 2
  • d) Unlimited
Show Answer

b) 1 - Exactly one abstract method; can have default/static methods.

2. What is the correct lambda syntax for no parameters?

  • a) -> expression
  • b) () -> expression
  • c) {} -> expression
  • d) _ -> expression
Show Answer

b) () -> expression - Empty parentheses required for no parameters.

3. Which built-in functional interface returns boolean?

  • a) Function
  • b) Consumer
  • c) Predicate
  • d) Supplier
Show Answer

c) Predicate - test() method returns boolean.

4. What is the method reference syntax for static methods?

  • a) ClassName.methodName
  • b) ClassName::methodName
  • c) ClassName->methodName
  • d) ClassName#methodName
Show Answer

b) ClassName::methodName - Double colon operator for method references.

5. Which stream operation is terminal?

  • a) filter()
  • b) map()
  • c) sorted()
  • d) collect()
Show Answer

d) collect() - Terminal operations produce results and end the stream.

6. Which stream operation removes duplicates?

  • a) unique()
  • b) distinct()
  • c) removeDuplicates()
  • d) filter()
Show Answer

b) distinct() - Returns stream with unique elements.

7. What does var keyword do in Java?

  • a) Creates dynamic type
  • b) Local variable type inference
  • c) Creates variant type
  • d) Disables type checking
Show Answer

b) Local variable type inference - Compiler infers type from initializer.

8. Which Java version introduced Records?

  • a) Java 8
  • b) Java 11
  • c) Java 14
  • d) Java 16
Show Answer

d) Java 16 - Records became standard in Java 16 (preview in 14/15).

9. What keyword is used in switch expressions to return a value from a block?

  • a) return
  • b) yield
  • c) break
  • d) give
Show Answer

b) yield - Used in switch expression blocks to return value.

10. Text blocks use which delimiter?

  • a) """
  • b) '''
  • c) ```
  • d) |||
Show Answer

a) """ - Triple double quotes for multi-line text blocks.

11. Which annotation marks a functional interface?

  • a) @Lambda
  • b) @FunctionalInterface
  • c) @SingleMethod
  • d) @Function
Show Answer

b) @FunctionalInterface - Optional but recommended annotation.

12. What does sealed class restrict?

  • a) Method access
  • b) Field access
  • c) Which classes can extend it
  • d) Object creation
Show Answer

c) Which classes can extend it - Uses permits keyword to list allowed subclasses.

13. Which stream method transforms elements?

  • a) filter()
  • b) map()
  • c) reduce()
  • d) peek()
Show Answer

b) map() - Transforms each element using a function.

14. Records are implicitly:

  • a) abstract
  • b) final
  • c) static
  • d) volatile
Show Answer

b) final - Records cannot be extended.

15. Base64.getEncoder() is used for:

  • a) Decoding Base64
  • b) Encoding to Base64
  • c) Encrypting data
  • d) Compressing data
Show Answer

b) Encoding to Base64 - Converts bytes to Base64 string.

Unit IV: Collections Framework

1. Which collection does not allow duplicates?

  • a) ArrayList
  • b) LinkedList
  • c) HashSet
  • d) Vector
Show Answer

c) HashSet - Set interface implementations don't allow duplicates.

2. Which collection maintains insertion order and allows duplicates?

  • a) HashSet
  • b) TreeSet
  • c) ArrayList
  • d) HashMap
Show Answer

c) ArrayList - List maintains order and allows duplicates.

3. Which Map implementation maintains sorted order?

  • a) HashMap
  • b) LinkedHashMap
  • c) TreeMap
  • d) Hashtable
Show Answer

c) TreeMap - Sorted by keys using natural ordering or Comparator.

4. Which collection is synchronized by default?

  • a) ArrayList
  • b) HashMap
  • c) Vector
  • d) LinkedList
Show Answer

c) Vector - Legacy class; thread-safe but slower.

5. What is the time complexity of ArrayList.get(index)?

  • a) O(1)
  • b) O(n)
  • c) O(log n)
  • d) O(n^2)
Show Answer

a) O(1) - Direct index access in array.

6. Iterator's remove() method removes:

  • a) First element
  • b) Last element
  • c) Current element
  • d) Next element
Show Answer

c) Current element - The last element returned by next().

7. Which interface is used for natural ordering?

  • a) Comparator
  • b) Comparable
  • c) Ordering
  • d) Sorted
Show Answer

b) Comparable - Defines compareTo() for natural ordering.

8. HashMap allows how many null keys?

  • a) 0
  • b) 1
  • c) 2
  • d) Unlimited
Show Answer

b) 1 - One null key, multiple null values allowed.

9. Which collection is best for frequent insertions/deletions?

  • a) ArrayList
  • b) LinkedList
  • c) Vector
  • d) Stack
Show Answer

b) LinkedList - O(1) insertion/deletion at known position.

10. PriorityQueue orders elements by:

  • a) Insertion order
  • b) Natural ordering or Comparator
  • c) Random order
  • d) Reverse order
Show Answer

b) Natural ordering or Comparator - Heap-based priority queue.

11. Which method of Comparable interface must be implemented?

  • a) compare()
  • b) compareTo()
  • c) equals()
  • d) compareWith()
Show Answer

b) compareTo() - Returns negative, zero, or positive integer.

12. LinkedHashSet maintains:

  • a) Sorted order
  • b) Insertion order
  • c) Random order
  • d) Reverse order
Show Answer

b) Insertion order - HashSet with linked list for ordering.

13. Hashtable vs HashMap - which allows null?

  • a) Both
  • b) Neither
  • c) Only HashMap
  • d) Only Hashtable
Show Answer

c) Only HashMap - Hashtable throws NullPointerException for null key/value.

14. Which Queue method removes and returns head, returning null if empty?

  • a) remove()
  • b) poll()
  • c) element()
  • d) peek()
Show Answer

b) poll() - remove() throws exception if empty.

15. Properties class extends:

  • a) HashMap
  • b) Hashtable
  • c) TreeMap
  • d) LinkedHashMap
Show Answer

b) Hashtable - Legacy class for configuration properties.

Unit V: Spring Framework Concepts

1. What does IoC stand for?

  • a) Input Output Control
  • b) Inversion of Control
  • c) Interface of Classes
  • d) Instance of Container
Show Answer

b) Inversion of Control - Container manages object creation and dependencies.

2. Which is the recommended type of dependency injection?

  • a) Field injection
  • b) Setter injection
  • c) Constructor injection
  • d) Method injection
Show Answer

c) Constructor injection - Promotes immutability and clear dependencies.

3. What is the default bean scope in Spring?

  • a) prototype
  • b) singleton
  • c) request
  • d) session
Show Answer

b) singleton - One instance per Spring container.

4. Which annotation marks a class as a Spring-managed service?

  • a) @Component
  • b) @Service
  • c) @Bean
  • d) Both a and b
Show Answer

d) Both a and b - @Service is a specialization of @Component.

5. AOP is used for handling:

  • a) Business logic
  • b) Cross-cutting concerns
  • c) Database operations
  • d) User interface
Show Answer

b) Cross-cutting concerns - Logging, security, transactions, etc.

6. Which advice type wraps the join point?

  • a) @Before
  • b) @After
  • c) @Around
  • d) @AfterReturning
Show Answer

c) @Around - Can control if/when the method executes.

7. @Autowired performs injection by:

  • a) Name
  • b) Type
  • c) Constructor
  • d) Index
Show Answer

b) Type - Matches by type; use @Qualifier for name.

8. Which annotation is used for initialization callback?

  • a) @Init
  • b) @PostConstruct
  • c) @AfterCreate
  • d) @Initialize
Show Answer

b) @PostConstruct - Called after dependency injection.

9. @RestController is equivalent to:

  • a) @Controller
  • b) @Controller + @ResponseBody
  • c) @Service + @ResponseBody
  • d) @Component + @REST
Show Answer

b) @Controller + @ResponseBody - Automatically serializes return values.

10. Which HTTP method is used to create a new resource?

  • a) GET
  • b) POST
  • c) PUT
  • d) DELETE
Show Answer

b) POST - Creates new resource; PUT updates existing.

11. @SpringBootApplication combines which annotations?

  • a) @Configuration, @EnableAutoConfiguration, @ComponentScan
  • b) @Controller, @Service, @Repository
  • c) @Bean, @Autowired, @Qualifier
  • d) @Primary, @Scope, @Lazy
Show Answer

a) @Configuration, @EnableAutoConfiguration, @ComponentScan

12. Which scope creates a new bean for each HTTP request?

  • a) singleton
  • b) prototype
  • c) request
  • d) session
Show Answer

c) request - Web-scoped bean; one per HTTP request.

13. @PathVariable extracts value from:

  • a) Query string
  • b) Request body
  • c) URI path
  • d) Header
Show Answer

c) URI path - e.g., /users/{id} extracts id.

14. Which runner interface receives raw command line arguments?

  • a) ApplicationRunner
  • b) CommandLineRunner
  • c) StartupRunner
  • d) InitRunner
Show Answer

b) CommandLineRunner - Receives String... args.

15. @Qualifier is used when:

  • a) No beans exist
  • b) Multiple beans of same type exist
  • c) Bean is prototype scoped
  • d) Bean needs lazy initialization
Show Answer

b) Multiple beans of same type exist - Specifies which bean to inject.