Important Java 8 Features MCQs

1 min read

Released in March 2014, Java 8 represents one of the most significant upgrades in the history of the Java programming language, introducing paradigm-shifting functional programming capabilities. Key additions include lambda expressions, the declarative Stream API for aggregate data processing, default and static methods in interfaces, and a robust, thread-safe java.time API. These enhancements dramatically reduce boilerplate code, improve application readability, and maximize multi-core processor efficiency through simplified parallel execution.

1. Which of the following is a major new feature introduced in Java 8?

a) Generics
b) Lambda Expressions
c) Annotations
d) Enums
Correct Answer: b) Lambda Expressions
Explanation:
Lambda expressions were a major feature introduced in Java 8 to support functional programming.

2. What is the primary purpose of a functional interface in Java 8?

a) To allow multiple inheritance
b) To contain only one abstract method
c) To provide default implementations
d) To act as a marker interface
Correct Answer: b) To contain only one abstract method
Explanation:
A functional interface contains exactly one abstract method, which can be implemented using a lambda expression.

3. Which annotation indicates that an interface is intended to be a functional interface?

a) @Functional
b) @SingleMethod
c) @FunctionalInterface
d) @LambdaInterface
Correct Answer: c) @FunctionalInterface
Explanation:
The @FunctionalInterface annotation ensures that the interface has only one abstract method at compile-time.

4. What is the correct syntax for a lambda expression in Java?

a) (parameters) -> { body }
b) { parameters } -> ( body )
c) (parameters) => { body }
d) parameters -> [ body ]
Correct Answer: a) (parameters) -> { body }
Explanation:
The correct syntax uses the arrow token '->' separating parameters and the body.

5. Which built-in functional interface represents a function that accepts one argument and returns a boolean?

a) Consumer
b) Supplier
c) Predicate
d) Function
Correct Answer: c) Predicate
Explanation:
The Predicate interface contains a test() method that accepts an argument and returns a boolean.

6. Which built-in functional interface takes one argument and returns no result?

a) Consumer
b) Supplier
c) Predicate
d) Function
Correct Answer: a) Consumer
Explanation:
The Consumer interface has an accept() method that takes an argument and returns void.

7. Which functional interface does not take any arguments but returns a result?

a) Consumer
b) Supplier
c) Predicate
d) Function
Correct Answer: b) Supplier
Explanation:
The Supplier interface has a get() method that takes no arguments and returns a result.

8. Which functional interface accepts one argument and produces a result of any type?

a) Consumer
b) Supplier
c) Predicate
d) Function
Correct Answer: d) Function
Explanation:
The Function interface takes an argument of type T and returns a result of type R.

9. What is the operator used for method references in Java 8?

a) ->
b) ::
c) .
d) :=
Correct Answer: b) ::
Explanation:
The double colon (::) is used for method references to point to a method by its name.

10. Which of the following is not a valid type of method reference?

a) Reference to a static method
b) Reference to an instance method of a particular object
c) Reference to a local variable
d) Reference to a constructor
Correct Answer: c) Reference to a local variable
Explanation:
Method references can only point to static methods, instance methods, and constructors.

11. What is the Java 8 Stream API primarily used for?

a) File I/O operations
b) Processing collections of objects sequentially or in parallel
c) Networking and socket programming
d) Creating graphical user interfaces
Correct Answer: b) Processing collections of objects sequentially or in parallel
Explanation:
The Stream API allows declarative processing of collections, supporting filtering, mapping, and reducing.

12. Which of the following Stream methods is an intermediate operation?

a) collect()
b) forEach()
c) filter()
d) count()
Correct Answer: c) filter()
Explanation:
Intermediate operations like filter() return a new Stream and are lazy.

13. Which of the following Stream methods is a terminal operation?

a) map()
b) reduce()
c) distinct()
d) sorted()
Correct Answer: b) reduce()
Explanation:
reduce() is a terminal operation that combines stream elements into a single result.

14. What does the Stream API map() method do?

a) It filters elements based on a condition
b) It sorts the elements in the stream
c) It applies a function to each element and returns a stream of the results
d) It combines all elements into a single result
Correct Answer: c) It applies a function to each element and returns a stream of the results
Explanation:
The map() method transforms each element in a stream by applying a specific function.

15. What is the primary difference between map() and flatMap() in the Stream API?

a) flatMap is used for arrays, map is for collections
b) map transforms elements, flatMap transforms and flattens multiple streams into one
c) map is terminal, flatMap is intermediate
d) flatMap returns a single value, map returns a stream
Correct Answer: b) map transforms elements, flatMap transforms and flattens multiple streams into one
Explanation:
flatMap() flattens complex structures like a Stream of Lists into a single Stream of elements.

16. How are intermediate operations executed in a Stream pipeline?

a) Immediately upon invocation
b) Eagerly to prepare the data
c) Lazily, only when a terminal operation is invoked
d) In parallel by default
Correct Answer: c) Lazily, only when a terminal operation is invoked
Explanation:
Intermediate operations are lazy; they are not executed until a terminal operation is triggered.

17. Which class was introduced in Java 8 to handle null references gracefully?

a) Nullable
b) Optional
c) NullHandler
d) NotNull
Correct Answer: b) Optional
Explanation:
The Optional class represents a value that might be present or absent, helping avoid NullPointerException.

18. How do you create an empty Optional object?

a) Optional.null()
b) Optional.ofNull()
c) Optional.empty()
d) new Optional()
Correct Answer: c) Optional.empty()
Explanation:
Optional.empty() returns an empty Optional instance with no value present.

19. What happens if you call Optional.of(null)?

a) It returns an empty Optional
b) It throws a NullPointerException
c) It returns an Optional containing null
d) It ignores the null and creates a default Optional
Correct Answer: b) It throws a NullPointerException
Explanation:
Optional.of() requires a non-null value. To handle potentially null values, use Optional.ofNullable().

20. Which method is used to retrieve a value from an Optional if it is present, and otherwise return a default value?

a) getOrDefault()
b) orElse()
c) ifPresent()
d) isPresent()
Correct Answer: b) orElse()
Explanation:
The orElse() method returns the value if present; otherwise, it returns the provided default value.

21. Can interfaces in Java 8 have method implementations?

a) No, interfaces can only have abstract methods
b) Yes, using the default and static keywords
c) Yes, but only using the final keyword
d) Yes, but only for private methods
Correct Answer: b) Yes, using the default and static keywords
Explanation:
Java 8 introduced default and static methods in interfaces, allowing them to contain concrete method bodies.

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

a) To replace abstract classes entirely
b) To enable multiple inheritance of state
c) To support backward compatibility when adding new methods to interfaces
d) To make interfaces faster
Correct Answer: c) To support backward compatibility when adding new methods to interfaces
Explanation:
Default methods allow new functionality to be added to interfaces without breaking existing implementing classes.

23. What happens if a class implements two interfaces that both have a default method with the same signature?

a) The code compiles and uses the first interface's method
b) The compiler throws an error indicating a conflict
c) The code compiles and executes both methods
d) The JVM chooses the method randomly at runtime
Correct Answer: b) The compiler throws an error indicating a conflict
Explanation:
This creates the Diamond Problem. The class must override the conflicting method to resolve the ambiguity.

24. Which package was introduced in Java 8 to replace the old Date and Calendar APIs?

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

25. Which class represents a date without a time in the Java 8 Date-Time API?

a) LocalTime
b) LocalDateTime
c) LocalDate
d) Date
Correct Answer: c) LocalDate
Explanation:
LocalDate represents a date (year, month, day) without a time or time zone.

26. Are the core classes in the new java.time package thread-safe?

a) No, they are mutable and not thread-safe
b) Yes, they are immutable and thread-safe
c) Thread safety must be handled using the synchronized keyword
d) Only LocalDateTime is thread-safe
Correct Answer: b) Yes, they are immutable and thread-safe
Explanation:
Unlike the legacy java.util.Date, the new java.time API classes are immutable and inherently thread-safe.

27. Which class is used to measure time in days, months, and years in Java 8?

a) Duration
b) Period
c) ChronoUnit
d) Temporal
Correct Answer: b) Period
Explanation:
The Period class models a quantity of time in terms of years, months, and days.

28. Which class is used to measure time in seconds and nanoseconds in Java 8?

a) Duration
b) Period
c) Interval
d) TimeSpan
Correct Answer: a) Duration
Explanation:
The Duration class measures time in seconds and nanoseconds, suitable for machine-based time measurement.

29. What does the forEach() method added to Iterable in Java 8 do?

a) Sorts the collection
b) Removes elements from the collection
c) Iterates over the elements and applies an action to each
d) Returns an iterator for the collection
Correct Answer: c) Iterates over the elements and applies an action to each
Explanation:
The forEach() method accepts a Consumer to perform an action on every element in an Iterable collection.

30. Which engine was introduced in Java 8 to execute JavaScript code from Java?

a) Rhino
b) V8
c) Nashorn
d) SpiderMonkey
Correct Answer: c) Nashorn
Explanation:
The Nashorn JavaScript engine was introduced in Java 8 to provide better performance than the older Rhino engine.

31. Which Java 8 feature allows an array to be sorted in parallel to improve performance on multicore systems?

a) Arrays.sort()
b) Arrays.parallelSort()
c) Collections.parallelSort()
d) Stream.sortParallel()
Correct Answer: b) Arrays.parallelSort()
Explanation:
Arrays.parallelSort() splits the array into subarrays, sorts them on different threads, and merges them.

32. What memory space was completely removed in Java 8?

a) Heap Space
b) Stack Memory
c) PermGen Space
d) Code Cache
Correct Answer: c) PermGen Space
Explanation:
The PermGen (Permanent Generation) memory space was removed in Java 8 and replaced by Metaspace.

33. Where does Metaspace store class metadata in Java 8?

a) In the Heap
b) In the PermGen
c) In native memory
d) In the Stack
Correct Answer: c) In native memory
Explanation:
Unlike PermGen, which resided in the JVM heap, Metaspace dynamically allocates memory from native OS memory.

34. Which class was added in Java 8 for native Base64 encoding and decoding?

a) java.util.Base64
b) sun.misc.BASE64Encoder
c) java.security.Base64
d) java.net.Base64
Correct Answer: a) java.util.Base64
Explanation:
Java 8 provided a standard java.util.Base64 class for encoding and decoding Base64 data.

35. What does a CompletableFuture in Java 8 provide over a traditional Future?

a) It uses fewer threads
b) It can be explicitly completed and supports non-blocking asynchronous callbacks
c) It is synchronous by default
d) It cannot handle exceptions
Correct Answer: b) It can be explicitly completed and supports non-blocking asynchronous callbacks
Explanation:
CompletableFuture supports chaining multiple async tasks and can be explicitly completed from any thread.

36. Which new class was introduced for joining Strings with a delimiter in Java 8?

a) StringBuilder
b) StringConcat
c) StringJoiner
d) StringFormatter
Correct Answer: c) StringJoiner
Explanation:
StringJoiner is used to construct a sequence of characters separated by a delimiter.

37. Which static method on the String class in Java 8 allows joining multiple strings with a delimiter?

a) String.concat()
b) String.merge()
c) String.join()
d) String.append()
Correct Answer: c) String.join()
Explanation:
String.join() is a static method introduced in Java 8 that utilizes StringJoiner internally.

38. What is the primary characteristic of a repeating annotation in Java 8?

a) It allows the same annotation to be applied multiple times to a single declaration
b) It repeats an annotation across multiple classes automatically
c) It loops through annotations at runtime
d) It creates an alias for an existing annotation
Correct Answer: a) It allows the same annotation to be applied multiple times to a single declaration
Explanation:
Java 8 introduced the @Repeatable meta-annotation, allowing developers to apply the same annotation multiple times.

39. Which Stream method returns the total number of elements in the stream?

a) size()
b) length()
c) count()
d) sum()
Correct Answer: c) count()
Explanation:
The count() method is a terminal operation that returns the number of elements in the stream.

40. What does the Stream.distinct() method do?

a) Sorts the stream
b) Removes duplicate elements based on their equals method
c) Reverses the stream
d) Filters out null values
Correct Answer: b) Removes duplicate elements based on their equals method
Explanation:
The distinct() method is an intermediate operation that returns a stream with unique elements.

41. What happens if you try to operate on a Java Stream after a terminal operation has been called?

a) The stream is reset and processed again
b) An IllegalStateException is thrown
c) The operation is silently ignored
d) The stream returns null
Correct Answer: b) An IllegalStateException is thrown
Explanation:
Streams are single-use; once a terminal operation is executed, the stream is considered consumed.

42. Which Collectors method is used to group stream elements by a specific property?

a) Collectors.partitioningBy()
b) Collectors.mapping()
c) Collectors.groupingBy()
d) Collectors.joining()
Correct Answer: c) Collectors.groupingBy()
Explanation:
Collectors.groupingBy() groups stream elements into a Map based on a classification function.

43. How many groups does Collectors.partitioningBy() create?

a) One
b) Exactly two
c) As many as there are unique keys
d) It depends on the input data size
Correct Answer: b) Exactly two
Explanation:
partitioningBy() splits the data into two lists inside a Map based on whether elements evaluate to true or false.

44. Which method is used to retrieve an optional value if present, or throw an exception if not?

a) orElse()
b) orElseGet()
c) orElseThrow()
d) getOrThrow()
Correct Answer: c) orElseThrow()
Explanation:
orElseThrow() returns the contained value if present; otherwise, it throws an exception.

45. Which local variable restriction applies to variables used inside a lambda expression?

a) They must be declared as static
b) They must be effectively final
c) They must be declared inside the lambda
d) They cannot be used at all
Correct Answer: b) They must be effectively final
Explanation:
Variables captured by a lambda expression from the enclosing scope must be final or effectively final.

46. Can a lambda expression access and modify instance variables of the enclosing class?

a) No, instance variables must also be effectively final
b) Yes, lambda expressions can freely read and modify instance variables
c) Only if the variables are marked as volatile
d) Only static variables can be modified
Correct Answer: b) Yes, lambda expressions can freely read and modify instance variables
Explanation:
The effectively final rule applies only to local variables. Instance variables can be modified.

47. Which Map method in Java 8 computes a value only if the specified key is not already associated with a value?

a) computeIfPresent()
b) putIfAbsent()
c) computeIfAbsent()
d) putOnly()
Correct Answer: c) computeIfAbsent()
Explanation:
computeIfAbsent() calculates a value and stores it only if the key is not already present or is mapped to null.

48. Which functional interface accepts two arguments and returns a result?

a) Function
b) BiFunction
c) Consumer
d) Predicate
Correct Answer: b) BiFunction
Explanation:
BiFunction takes two arguments and returns a result.

49. What is the difference between Function and UnaryOperator?

a) There is no difference
b) UnaryOperator requires the input and output to be of the same type
c) Function requires the input and output to be of the same type
d) UnaryOperator takes no arguments
Correct Answer: b) UnaryOperator requires the input and output to be of the same type
Explanation:
UnaryOperator extends Function, enforcing that the return type matches the argument type.

50. Which Stream method allows you to execute an action on each element without consuming the stream?

a) map()
b) forEach()
c) peek()
d) trace()
Correct Answer: c) peek()
Explanation:
peek() is an intermediate operation that performs an action on each element without terminating the pipeline.

51. Which class represents an immutable date and time with a time-zone in Java 8?

a) LocalDateTime
b) OffsetDateTime
c) ZonedDateTime
d) TimeZoneDate
Correct Answer: c) ZonedDateTime
Explanation:
ZonedDateTime handles date and time calculations involving specific geographical time zones.

52. Which class was introduced to represent a point in time on the timeline in Java 8?

a) EpochTime
b) Instant
c) Timestamp
d) PointInTime
Correct Answer: b) Instant
Explanation:
The Instant class models a single instantaneous point on the time-line, typically used for timestamps.

53. What does Collection.removeIf() do?

a) Removes the first element matching a predicate
b) Removes all elements that satisfy a given Predicate
c) Removes elements based on index
d) Clears the entire collection
Correct Answer: b) Removes all elements that satisfy a given Predicate
Explanation:
removeIf() iterates and removes elements satisfying the provided Predicate.

54. How do you generate an infinite sequential unordered stream in Java 8?

a) Stream.iterate()
b) Stream.generate()
c) Stream.infinite()
d) Stream.loop()
Correct Answer: b) Stream.generate()
Explanation:
Stream.generate() takes a Supplier and produces an infinite, unordered stream of elements.

55. How do you generate an infinite sequential ordered stream in Java 8?

a) Stream.iterate()
b) Stream.generate()
c) Stream.ordered()
d) Stream.sequence()
Correct Answer: a) Stream.iterate()
Explanation:
Stream.iterate() takes a seed value and a UnaryOperator to produce an infinite, sequentially ordered stream.

56. Which method is used to skip the first N elements of a Stream?

a) jump(n)
b) ignore(n)
c) skip(n)
d) pass(n)
Correct Answer: c) skip(n)
Explanation:
The skip(n) intermediate operation returns a stream that discards the first n elements.

57. Which method is used to truncate a Stream so it contains no more than N elements?

a) limit(n)
b) truncate(n)
c) max(n)
d) cut(n)
Correct Answer: a) limit(n)
Explanation:
The limit(n) intermediate operation returns a stream constrained to be no longer than n elements.

58. What does Stream.anyMatch() return?

a) An Optional containing the first matching element
b) A boolean true if at least one element matches the provided predicate
c) A list of all matching elements
d) A boolean true only if all elements match the predicate
Correct Answer: b) A boolean true if at least one element matches the provided predicate
Explanation:
anyMatch() is a short-circuiting operation returning true as soon as it finds a matching element.

59. What happens if Stream.allMatch() is called on an empty stream?

a) It throws an exception
b) It returns false
c) It returns true
d) It returns an empty Optional
Correct Answer: c) It returns true
Explanation:
By definition of vacuous truth, all elements of an empty set satisfy any condition, so allMatch() returns true.

60. Which class is introduced in Java 8 for fast concurrent lock-free counters?

a) AtomicInteger
b) LongAdder
c) SynchronizedCounter
d) VolatileLong
Correct Answer: b) LongAdder
Explanation:
LongAdder is designed for high-contention environments where multiple threads update a common sum.

61. What new locking mechanism was introduced in java.util.concurrent.locks in Java 8?

a) ReentrantLock
b) ReadWriteLock
c) StampedLock
d) SpinLock
Correct Answer: c) StampedLock
Explanation:
StampedLock provides an optimistic read lock that improves throughput in read-heavy concurrent scenarios.

62. What does List.replaceAll() do in Java 8?

a) Replaces all elements with a single provided value
b) Replaces each element with the result of applying a given UnaryOperator
c) Removes all existing elements and adds new ones
d) Finds a specific element and replaces all its occurrences
Correct Answer: b) Replaces each element with the result of applying a given UnaryOperator
Explanation:
List.replaceAll() replaces every item in the list with the result of applying the operator to that item.

63. Can Java 8 interfaces have constructors?

a) Yes, if they only have default methods
b) No, interfaces can never have constructors
c) Yes, but they must be private
d) Yes, introduced alongside default methods
Correct Answer: b) No, interfaces can never have constructors
Explanation:
Even with default and static methods, interfaces cannot maintain state and thus cannot have constructors.

64. What is the return type of the Stream.min() and Stream.max() methods?

a) The element itself
b) An Optional containing the element
c) An integer representing the index
d) null if the stream is empty
Correct Answer: b) An Optional containing the element
Explanation:
min() and max() return an Optional because the stream might be empty, and no value would exist.

65. Which of the following creates a stream from an array in Java 8?

a) Stream.of(array)
b) Arrays.stream(array)
c) Both a and b
d) Array.toStream(array)
Correct Answer: c) Both a and b
Explanation:
Both Arrays.stream(array) and Stream.of(array) can convert an array into a Stream.

66. What is the purpose of the Spliterator interface in Java 8?

a) To split strings easily
b) To iterate and partition elements for parallel execution
c) To split large files into chunks
d) To replace the Iterator interface completely
Correct Answer: b) To iterate and partition elements for parallel execution
Explanation:
Spliterator (Splitable Iterator) supports parallel processing by traversing and splitting data structures.

67. How do you convert a sequential Stream into a parallel Stream?

a) stream.parallel()
b) stream.toParallel()
c) stream.asParallel()
d) Stream.parallelize(stream)
Correct Answer: a) stream.parallel()
Explanation:
Calling parallel() on a stream converts it to a parallel stream executing on multiple threads.

68. Which thread pool is used by parallel streams by default?

a) FixedThreadPool
b) CachedThreadPool
c) ForkJoinPool.commonPool()
d) SingleThreadExecutor
Correct Answer: c) ForkJoinPool.commonPool()
Explanation:
Parallel streams utilize the common ForkJoinPool, dynamically adapting to available processor cores.

69. Which primitive stream types were introduced to avoid boxing overhead in Java 8?

a) IntStream, LongStream, DoubleStream
b) ByteStream, ShortStream, FloatStream
c) IntegerStream, LongStream, BooleanStream
d) PrimitiveStream
Correct Answer: a) IntStream, LongStream, DoubleStream
Explanation:
These specialized streams handle primitive data types without the performance penalty of auto-boxing.

70. What does IntStream.range(1, 5) produce?

a) 1, 2, 3, 4, 5
b) 1, 2, 3, 4
c) 2, 3, 4
d) An error
Correct Answer: b) 1, 2, 3, 4
Explanation:
range(start, end) produces an exclusive upper bound, so it generates 1, 2, 3, and 4.

71. What does IntStream.rangeClosed(1, 5) produce?

a) 1, 2, 3, 4, 5
b) 1, 2, 3, 4
c) 2, 3, 4
d) An error
Correct Answer: a) 1, 2, 3, 4, 5
Explanation:
rangeClosed(start, end) produces an inclusive upper bound, generating 1 through 5.

72. How do you conditionally execute code if an Optional contains a value?

a) optional.getIfPresent(Consumer)
b) optional.ifPresent(Consumer)
c) optional.check(Consumer)
d) optional.execute(Consumer)
Correct Answer: b) optional.ifPresent(Consumer)
Explanation:
The ifPresent() method executes the provided Consumer block only if a value is present.

73. Which functional interface defines custom comparison logic for sorting a stream?

a) Comparable
b) Comparator
c) Sorter
d) Predicate
Correct Answer: b) Comparator
Explanation:
The Comparator functional interface is used in Stream.sorted() to define custom sorting.

74. What method in the Math class safely adds two integers and throws an ArithmeticException on overflow?

a) Math.addExact()
b) Math.safeAdd()
c) Math.addSafe()
d) Math.sum()
Correct Answer: a) Math.addExact()
Explanation:
Java 8 introduced exact math methods like addExact() to detect arithmetic overflows.

75. Can you define the Object class methods (like equals, hashCode) as default methods in an interface?

a) Yes, it is perfectly legal
b) No, it causes a compile-time error
c) Yes, but they must be private
d) Yes, but they must be static
Correct Answer: b) No, it causes a compile-time error
Explanation:
Default methods cannot override methods from java.lang.Object.

76. What is the result of applying map() on an empty Optional?

a) NullPointerException
b) It returns a new empty Optional
c) It throws NoSuchElementException
d) It returns null
Correct Answer: b) It returns a new empty Optional
Explanation:
If the Optional is empty, calling map() simply returns an empty Optional.

77. Which utility class was enhanced with a parallelSort method in Java 8?

a) Collections
b) Arrays
c) Lists
d) System
Correct Answer: b) Arrays
Explanation:
The java.util.Arrays class was enhanced with parallelSort() to sort arrays concurrently.

78. What is type inference in the context of Java 8 lambda expressions?

a) The compiler deducting lambda parameter types
b) A way to cast objects implicitly
c) A runtime mechanism to determine object types
d) The mandatory declaration of parameter types
Correct Answer: a) The compiler deducting lambda parameter types
Explanation:
Type inference allows omitting parameter types in a lambda expression, as the compiler infers them.

79. Which class formats and parses dates in the new Java 8 Time API?

a) SimpleDateFormat
b) DateTimeFormatter
c) DateFormat
d) TimeFormatter
Correct Answer: b) DateTimeFormatter
Explanation:
DateTimeFormatter in java.time.format replaces SimpleDateFormat and is thread-safe.

80. What is the difference between findFirst() and findAny() in Streams?

a) findFirst() works on lists, findAny() on sets
b) findFirst() is deterministic, findAny() can return any element
c) There is no difference
d) findAny() throws an exception if the stream is empty
Correct Answer: b) findFirst() is deterministic, findAny() can return any element
Explanation:
findFirst() returns the first element in order, whereas findAny() is optimized for parallel processing.

81. What does the Map.merge() method do in Java 8?

a) Merges two maps together
b) Updates an existing value or inserts a new value based on a given BiFunction
c) Removes duplicates from a Map
d) Converts a Map to a List
Correct Answer: b) Updates an existing value or inserts a new value based on a given BiFunction
Explanation:
Map.merge() combines an existing value and a new value using a mapping function.

82. What does String.chars() introduced in Java 8 return?

a) An array of characters
b) An IntStream representing the characters
c) A Stream of Characters
d) A List of Characters
Correct Answer: b) An IntStream representing the characters
Explanation:
String.chars() returns an IntStream representing the characters in the string.

83. Which method on CompletableFuture allows running an async task without returning a result?

a) supplyAsync()
b) runAsync()
c) executeAsync()
d) startAsync()
Correct Answer: b) runAsync()
Explanation:
runAsync() accepts a Runnable and returns a CompletableFuture representing no result.

84. Which method on CompletableFuture allows running an async task that returns a result?

a) supplyAsync()
b) runAsync()
c) fetchAsync()
d) getAsync()
Correct Answer: a) supplyAsync()
Explanation:
supplyAsync() accepts a Supplier and returns a CompletableFuture holding the result.

85. In Java 8, can you annotate a variable type?

a) No, annotations are only for declarations
b) Yes, annotations can be applied anywhere a type is used
c) Yes, but only for local variables
d) No, this feature was introduced in Java 11
Correct Answer: b) Yes, annotations can be applied anywhere a type is used
Explanation:
Java 8 introduced Type Annotations, allowing annotations on any type use (e.g., casts, throws clauses).

86. What does Map.getOrDefault(key, defaultValue) do?

a) Returns the value for the key, or throws an exception
b) Returns the value for the key, or returns defaultValue if key is missing
c) Inserts the defaultValue into the map if missing
d) Removes the key if its value matches defaultValue
Correct Answer: b) Returns the value for the key, or returns defaultValue if key is missing
Explanation:
getOrDefault() retrieves the value or falls back to a provided default without modifying the map.

87. Which functional interface modifies object state without returning anything?

a) Function
b) Supplier
c) Predicate
d) Consumer
Correct Answer: d) Consumer
Explanation:
A Consumer accepts an argument and performs side-effects without returning a result.

88. What is the main advantage of primitive streams like IntStream over Stream of Integers?

a) They provide more intermediate operations
b) They avoid the performance overhead of boxing and unboxing
c) They run in parallel by default
d) They prevent null values automatically
Correct Answer: b) They avoid the performance overhead of boxing and unboxing
Explanation:
Primitive streams handle primitives directly, skipping auto-boxing overhead.

89. Which method is used to convert an IntStream back to a Stream of Integer objects?

a) toObjectStream()
b) box()
c) boxed()
d) wrap()
Correct Answer: c) boxed()
Explanation:
The boxed() method converts a primitive stream into a stream of wrapper objects.

90. Which feature of CompletableFuture combines two independent asynchronous tasks once both complete?

a) thenCompose()
b) thenCombine()
c) thenApply()
d) allOf()
Correct Answer: b) thenCombine()
Explanation:
thenCombine() allows you to execute a BiFunction when both CompletableFutures have completed.

91. Which CompletableFuture method is used to chain a dependent asynchronous task?

a) thenCompose()
b) thenCombine()
c) thenApply()
d) thenRun()
Correct Answer: a) thenCompose()
Explanation:
thenCompose() is similar to flatMap; it takes the result of the first future and returns a new future.

92. Which of these is the correct way to sort a list of Strings by length using Java 8?

a) list.sort(String::length)
b) list.sort(Comparator.comparing(String::length))
c) Collections.sort(list, String::length)
d) list.sortedByLength()
Correct Answer: b) list.sort(Comparator.comparing(String::length))
Explanation:
Comparator.comparing() takes a key extractor function to create a comparator.

93. Which interface represents a Supplier of primitive boolean values in Java 8?

a) Predicate
b) BooleanSupplier
c) Supplier of Boolean
d) Condition
Correct Answer: b) BooleanSupplier
Explanation:
BooleanSupplier provides getAsBoolean(), avoiding the overhead of Boolean objects.

94. What is the use of the DoubleAdder class in Java 8?

a) To sort doubles efficiently
b) To maintain a highly concurrent running sum of double values
c) To convert Strings to doubles
d) To generate random double streams
Correct Answer: b) To maintain a highly concurrent running sum of double values
Explanation:
DoubleAdder is designed for high-performance concurrent accumulation of double values.

95. Which Stream terminal operation converts elements into a String and concatenates them?

a) Collectors.concat()
b) Collectors.joining()
c) Collectors.toString()
d) Collectors.merging()
Correct Answer: b) Collectors.joining()
Explanation:
Collectors.joining() concatenates stream elements into a String.

96. What does Files.lines(Path) do in Java 8?

a) Returns a List of Strings representing file lines
b) Returns a Stream of Strings representing the lines of a file lazily
c) Reads the entire file into a single String
d) Returns a character array of the file contents
Correct Answer: b) Returns a Stream of Strings representing the lines of a file lazily
Explanation:
Files.lines() returns a Stream, processing large files efficiently without loading them into memory entirely.

97. What does the Optional.flatMap() method do?

a) Applies a function returning an Optional and prevents nested Optionals
b) Converts an Optional to a Stream
c) Flattens a List of Optionals into a single List
d) Behaves exactly like map()
Correct Answer: a) Applies a function returning an Optional and prevents nested Optionals
Explanation:
flatMap() prevents you from getting an Optional containing another Optional.

98. What is the correct syntax for a constructor reference in Java 8?

a) ClassName::new
b) ClassName.new()
c) ClassName::constructor
d) new::ClassName
Correct Answer: a) ClassName::new
Explanation:
Constructor references use the ClassName followed by :: and the keyword new.

99. In the java.time API, how do you get the current date?

a) LocalDate.now()
b) Date.today()
c) LocalDate.today()
d) Time.now()
Correct Answer: a) LocalDate.now()
Explanation:
The now() static method on LocalDate obtains the current date from the system clock.

100. How do you parse a string into a LocalDate in Java 8?

a) LocalDate.fromString('2023-01-01')
b) LocalDate.parse('2023-01-01')
c) LocalDate.valueOf('2023-01-01')
d) new LocalDate('2023-01-01')
Correct Answer: b) LocalDate.parse('2023-01-01')
Explanation:
The parse() method is used to convert a string representation into a date/time object.

101. Which interface was added in Java 8 to support unsigned integer operations?

a) UnsignedInteger
b) Methods were added to the Integer wrapper class natively
c) UInt
d) PositiveInteger
Correct Answer: b) Methods were added to the Integer wrapper class natively
Explanation:
Java 8 added methods like Integer.parseUnsignedInt() natively to the Integer class.

102. What is a major difference between Collection and Stream in Java 8?

a) Streams hold data, Collections do not
b) Collections can be iterated multiple times, Streams can only be consumed once
c) Streams allow modifications to elements
d) Collections are lazy, Streams are eager
Correct Answer: b) Collections can be iterated multiple times, Streams can only be consumed once
Explanation:
A Stream is not a data structure and cannot be reused after a terminal operation.

103. Which concurrent class heavily supports parallel streams in Java 8?

a) ExecutorService
b) ForkJoinPool
c) ThreadPoolExecutor
d) ScheduledExecutorService
Correct Answer: b) ForkJoinPool
Explanation:
Java 8 parallel streams rely on ForkJoinPool.commonPool() for execution.

104. What is the output of Optional.ofNullable(null).isPresent()?

a) true
b) false
c) NullPointerException
d) Compilation error
Correct Answer: b) false
Explanation:
ofNullable(null) creates an empty Optional, so isPresent() returns false.

105. Which functional interface takes two arguments of the same type and returns a result of the same type?

a) BiFunction
b) BinaryOperator
c) BiConsumer
d) DoubleFunction
Correct Answer: b) BinaryOperator
Explanation:
BinaryOperator extends BiFunction and requires both arguments and the result to be of the same type.

106. Which of the following is true regarding default methods in interfaces?

a) They must be declared as final
b) They cannot be overridden by implementing classes
c) They can be overridden by implementing classes
d) They can access instance variables of the interface
Correct Answer: c) They can be overridden by implementing classes
Explanation:
Implementing classes can use the default implementation or override it.

107. Can an interface have multiple default methods in Java 8?

a) Yes
b) No, only one default method is allowed per interface
c) Only if it is a functional interface
d) Only if they have different return types
Correct Answer: a) Yes
Explanation:
An interface can have any number of default methods.

108. Which Stream method safely returns an Optional containing the first element, handling empty streams?

a) first()
b) findFirst()
c) get()
d) find()
Correct Answer: b) findFirst()
Explanation:
findFirst() returns an Optional describing the first element of the stream.

109. What is the primary advantage of the new java.time API over java.util.Date?

a) It uses fewer classes
b) It is mutable for better performance
c) It is immutable, thread-safe, and clearly separates human and machine time
d) It relies heavily on the legacy Calendar class
Correct Answer: c) It is immutable, thread-safe, and clearly separates human and machine time
Explanation:
The java.time API makes date objects immutable and inherently safe for multi-threading.

110. Which functional interface does the Stream.filter() method accept?

a) Function
b) Consumer
c) Predicate
d) Supplier
Correct Answer: c) Predicate
Explanation:
filter() requires a boolean condition provided by the Predicate functional interface.

111. What does Collectors.summarizingInt() return?

a) Only the sum of elements
b) Only the average of elements
c) An IntSummaryStatistics object containing count, sum, min, max, and average
d) An integer array
Correct Answer: c) An IntSummaryStatistics object containing count, sum, min, max, and average
Explanation:
summarizingInt() gathers all statistical data in a single pass.

112. How do you check if a year is a leap year using the Java 8 Date API?

a) LocalDate.now().isLeapYear()
b) Date.isLeapYear()
c) Year.now().isLeapYear()
d) Both a and c
Correct Answer: d) Both a and c
Explanation:
Both LocalDate and Year classes provide an isLeapYear() method.

113. Which of the following describes a short-circuiting operation in streams?

a) An operation that throws an exception
b) An operation that can produce a finite result from an infinite stream
c) An operation that ignores errors
d) An operation that executes on a single thread
Correct Answer: b) An operation that can produce a finite result from an infinite stream
Explanation:
Operations like limit() or findFirst() are short-circuiting because they terminate early.

114. What is the return type of the thenApply() method in CompletableFuture?

a) void
b) Future
c) CompletableFuture
d) The generic type T
Correct Answer: c) CompletableFuture
Explanation:
thenApply() transforms the result and returns a new CompletableFuture.

115. How does CompletableFuture handle exceptions?

a) It ignores them
b) It crashes the application
c) It uses methods like exceptionally() to manage exceptions
d) It requires try-catch blocks inside every lambda
Correct Answer: c) It uses methods like exceptionally() to manage exceptions
Explanation:
CompletableFuture provides functional error handling through exceptionally() and handle().

116. Which Map method replaces an entry only if it is mapped to a specific value?

a) replace(K key, V oldValue, V newValue)
b) update(K key, V value)
c) putIfPresent()
d) swap()
Correct Answer: a) replace(K key, V oldValue, V newValue)
Explanation:
The conditional replace() method safely updates a value only if the current value matches.

117. What happens if you invoke a default method using a lambda expression directly?

a) It executes the default method
b) Lambdas only implement the abstract method; default methods cannot be invoked directly from the lambda body via 'this'
c) It throws a compilation error
d) The JVM crashes
Correct Answer: b) Lambdas only implement the abstract method; default methods cannot be invoked directly from the lambda body via 'this'
Explanation:
A lambda provides the implementation for the single abstract method and does not inherit 'this' from the interface.

118. Can you use the 'this' keyword inside a lambda expression?

a) No, it is strictly forbidden
b) Yes, but it refers to the anonymous class
c) Yes, and it refers to the enclosing instance where the lambda is defined
d) Yes, but it refers to the interface itself
Correct Answer: c) Yes, and it refers to the enclosing instance where the lambda is defined
Explanation:
Lambdas do not create their own scope; 'this' refers to the enclosing object.
← Previous: Core Java MCQs
Next →: Java Advanced MCQs
No Image

C++ Exception / Error Handling - MCQs

1. Which of the following is a major new feature introduced in Java 8? a) Generics b) Lambda Expressions c)…

By MCQs Generator
Latest Java Generics MCQs

Latest Java Generics MCQs

Java generics introduce compile-time type safety and reusability by allowing classes, interfaces, and methods to operate on parameterized types. Introduced…

By MCQs Generator
JavaScript Operators MCQs

JavaScript Operators MCQs

JavaScript operators are foundational symbols and keywords used to manipulate data, perform mathematical computations, assign values, and control programmatic flow…

By MCQs Generator