Java Chapter 8 Part 1 Flashcards

(399 cards)

1
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is a lambda expression in Java?

A

A lambda expression is an anonymous function (method without a name) that provides a concise way to implement functional interfaces and can be passed around like objects.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the four key characteristics of lambda expressions mentioned in the text?

A

1) Anonymous (no explicit name), 2) Concise (shorter than anonymous classes), 3) Functional (represents behavior), 4) Passable (can be stored in variables or passed to methods)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Given the Animal record:

A

java Animal animal = new Animal(“Kangaroo”, true, false); CheckTrait hopper = a -> a.canHop(); boolean canHop = hopper.test(animal);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What interface would you need to create to use with the Animal record for trait checking, as shown in the example?

A

java public interface CheckTrait { boolean test(Animal a); }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How would you rewrite the following class using a lambda expression?

A

java CheckTrait hopper = a -> a.canHop();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What Java version introduced lambda expressions?

A

Java 8 introduced lambda expressions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is the main advantage of using lambda expressions over traditional class implementations for functional interfaces?

A

Lambdas provide a more concise syntax by eliminating the need to create entire classes just to encapsulate one piece of functionality.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Given the Animal record and CheckTrait interface, what would be the output of:

A

The output would be true because the fish can swim (canSwim = true).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What type of programming paradigm do lambda expressions support in Java?

A

Lambda expressions support functional programming paradigms in Java.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

In the context of the Animal example, why is the CheckTrait interface considered a functional interface?

A

It’s a functional interface because it contains exactly one abstract method (test(Animal a)), which is the requirement for an interface to be used with lambda expressions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

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

A

The basic syntax is: (parameters) -> { body }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Given the lambda expression CheckTrait hopper = a -> a.canHop();, what interface must CheckTrait be to make this valid?

A

CheckTrait must be a functional interface with exactly one abstract method that takes one parameter and returns a boolean.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What will this code output?

A

It will output true because the lambda checks if the kangaroo can hop.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Which package contains Java’s built-in functional interfaces like Predicate and Function?

A

java.util.function

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the key characteristic that makes an interface a “functional interface” in Java?

A

It must contain exactly one abstract method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Which built-in functional interface would you use for an operation that takes one input and returns a boolean result?

A

Predicate<T></T>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What types of variables can a lambda access from its enclosing scope?

A

1) Its own parameters, 2) final or effectively final variables from enclosing scope, 3) instance variables.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What are two benefits of using lambda expressions in Java?

A

1) Conciseness (reduced boilerplate code), 2) Improved readability (clearer intent).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Given this code, what is wrong with the lambda expression?

A

The lambda is trying to modify count which isn’t final or effectively final - this will cause a compilation error.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Which functional interface would be most appropriate for a operation that takes no input but produces a result?

A

Supplier<T></T>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is the equivalent method reference for the lambda expression a -> a.canHop() when implementing the CheckTrait functional interface?

A

Animal::canHop

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Given the following code snippet from the OCA exam, what does the lambda expression a -> a.canSwim() represent?

A

It represents an implementation of the CheckTrait functional interface that tests if an Animal can swim.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

In the context of Java lambdas, what is the purpose of the print() method in this code?

A

It filters and prints animals from a list based on the behavior defined in the CheckTrait lambda or method reference.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Which Java feature allows lambdas to work with interfaces like CheckTrait without requiring full class implementations?
Functional interfaces (interfaces with exactly one abstract method).
26
What is the primary advantage of using method references over lambdas in Java, as shown in this comparison?
Method references provide shorter, more readable syntax when the lambda simply calls an existing method.
27
In the given animal filtering example, why is this approach better than creating separate classes for each check?
It eliminates boilerplate code, makes behavior more flexible, and keeps the logic where it's used.
28
What are the five key takeaways about lambdas and functional interfaces from the text?
Lambdas are anonymous functions for passing behavior as arguments Functional interfaces have exactly one abstract method Lambdas work with functional interfaces for concise implementations Leads to more flexible and readable code Method references provide even shorter syntax when appropriate
29
What is the main problem demonstrated by the TraditionalSearch class when implementing the CheckTrait interface without lambdas?
It requires creating separate classes (like CheckIfHopper) for each simple condition check, leading to code clutter and verbosity.
30
In the TraditionalSearch class, what is the purpose of the print method's second parameter CheckTrait checker?
It accepts an implementation of the CheckTrait interface to test each Animal object against a specific condition.
31
Given the TraditionalSearch class, how would you modify it to check for swimming animals without lambdas?
You would need to create a new class implementing CheckTrait: java class CheckIfSwimmer implements CheckTrait { public boolean test(Animal a) { return a.canSwim(); } } Then call: print(animals, new CheckIfSwimmer());
32
What design pattern does the TraditionalSearch class exemplify when using CheckIfHopper?
It demonstrates the Strategy pattern, where different algorithms (checking behaviors) can be selected at runtime.
33
How many additional classes would be needed to check for 3 different animal traits using the traditional approach shown in TraditionalSearch?
Three separate classes (one for each trait check), each implementing the CheckTrait interface.
34
In the print method of TraditionalSearch, what does the line if (checker.test(animal)) accomplish?
It calls the implemented test method from the CheckTrait interface on the current animal object, returning true if the animal meets the specified condition.
35
What would be the output of the TraditionalSearch program if the Animal objects were initialized as shown and only CheckIfHopper was used?
It would print "kangaroo rabbit" since these are the hopping animals in the list.
36
Why does the traditional approach shown in TraditionalSearch violate the DRY (Don't Repeat Yourself) principle?
Because each new condition check requires creating a new class with similar boilerplate code, just changing the condition logic.
37
What is the lambda expression equivalent to the CheckIfHopper class in the following code?
The lambda a -> a.canHop() replaces the need for a separate CheckIfHopper class implementation of the CheckTrait interface.
38
How would you write a lambda expression to filter animals that can swim using the print method?
java print(animals, a -> a.canSwim());
39
What three key concepts enable lambdas to work in Java (as shown in the example)?
1) Functional Interface Context, 2) Type Inference, 3) Deferred Execution.
40
Why can Java infer that a is an Animal in the lambda a -> a.canHop()?
Because the CheckTrait functional interface's method test(Animal a) declares the parameter as an Animal.
41
When is the code in a lambda expression executed?
It's executed when the containing method (like print()) calls the functional interface's method (checker.test(animal)), not when the lambda is defined.
42
What is the basic syntax structure of a lambda expression?
(parameters) -> { body }
43
How would you write a lambda with a single parameter (type inferred) to check if an animal cannot swim?
java print(animals, a -> !a.canSwim());
44
How would you write a lambda with multiple parameters to check if one animal can hop and another can swim?
java (a, b) -> a.canHop() && b.canSwim()
45
What is required in a lambda body when it contains multiple statements?
The body must be enclosed in braces {} and include an explicit return statement if returning a value.
46
What would be the correct lambda syntax for an operation that prints an animal before checking if it can hop?
java a -> { System.out.println("Checking animal: " + a); return a.canHop(); }
47
What are four advantages of using lambda expressions in Java, as mentioned in the text?
1) Reduced boilerplate code, 2) Improved readability, 3) Increased flexibility, 4) Better maintainability.
48
In the LambdaSearch class example, what does the following line of code do? print(animals, a -> a.canHop());
It prints all animals from the list that can hop by using a lambda expression to test each animal's canHop() capability.
49
What would the line print(animals, a -> !a.canSwim()); output from the given Animal list?
It would output "kangaroo rabbit" because these are the animals that cannot swim (!canSwim).
50
What is the purpose of the CheckTrait interface in the lambda example (implied by the usage)?
The CheckTrait interface likely contains a single abstract method (SAM) that takes an Animal parameter and returns a boolean, enabling the lambda expressions.
51
How does the following lambda expression work in the print method? a -> a.species().equals("fish")
It tests each Animal object 'a', returning true if the animal's species is "fish", thus including it in the output.
52
What principle of lambda expressions is demonstrated by having multiple different checks (hoppers, swimmers, etc.) using the same print method?
It demonstrates behavior parameterization - passing different behaviors (lambda expressions) to the same method.
53
In the context of the Animal class usage, what would be the correct way to write a lambda expression to find all animals that can swim but cannot hop?
a -> a.canSwim() && !a.canHop()
54
What Java feature allows the lambda expression a -> a.canHop() to be valid despite not specifying types?
Type inference - Java infers the parameter 'a' is of type Animal from the context of the CheckTrait interface.
55
Why is the print method able to work with different lambda expressions without modification?
Because it accepts a CheckTrait parameter, and lambda expressions implement this functional interface polymorphically.
56
What would be the traditional (non-lambda) way to implement the fish-checking functionality shown in the example?
By creating a separate class that implements CheckTrait with a test() method containing return animal.species().equals("fish");
57
What are the two syntax variations for writing the same lambda expression to check if an Animal can hop?
Concise form: a -> a.canHop() Verbose form: (Animal a) -> { return a.canHop(); }
58
In the concise lambda form a -> a.canHop(), why don't we need to specify the parameter type?
The type is inferred from the context (CheckTrait interface) through Java's type inference system.
59
What are the three components omitted in the concise lambda form a -> a.canHop() compared to its verbose equivalent?
No parameter type (just a instead of (Animal a)) No braces {} around the body No return keyword or semicolon
60
Given the verbose lambda (Animal a) -> { return a.canHop(); }, which elements would become optional if we converted it to concise form?
The parentheses around parameter, braces, return keyword, and semicolon would all become optional.
61
What would happen if you tried to compile this lambda with incorrect syntax: a -> { a.canHop() }?
It would fail to compile because a block-bodied lambda with a return value must use the return keyword (missing in this case).
62
When should you prefer the verbose form of lambda expression over the concise form?
When you need multiple statements, when explicit types improve clarity, or when working with complex logic.
63
In the method call print(animals, a -> a.canHop());, how does Java determine the type of parameter 'a'?
Java's type inference system determines it from the expected functional interface type (CheckTrait in this case).
64
Which of these is NOT valid syntax for a lambda expression that checks if an Animal can hop?
java a -> return a.canHop() This is invalid because when using return, you must include braces for a block body.
65
What makes the following lambda expression valid despite its minimal syntax: a -> a.canHop()?
It's valid because: Single parameter doesn't need parentheses Single expression doesn't need braces or return Type is inferred from context
66
What would be the correct way to write a multi-statement lambda that checks if an Animal can hop and prints the result?
java a -> { boolean canHop = a.canHop(); System.out.println(canHop); return canHop; }
67
Given the functional interface CheckTrait with method boolean test(Animal a), which of these lambda expressions is valid syntax for no parameters?
java () -> new Animal("default", false, false)
68
What is the correct lambda syntax for multiple parameters (without explicit types) that checks if one animal can hop and another can swim?
java (a1, a2) -> a1.canHop() && a2.canSwim()
69
How would you write a lambda expression with explicit Animal types for two parameters comparing their species?
java (Animal a1, Animal a2) -> a1.species().equals(a2.species())
70
What is the proper multi-line lambda syntax that prints an animal's species before returning whether it can hop?
java a -> { System.out.println("Checking: " + a.species()); return a.canHop(); }
71
Given CheckTrait's test(Animal a) method, why must the lambda parameter a be an Animal type?
Because the functional interface method signature enforces the parameter type as Animal.
72
What return type must the body of a lambda implementing CheckTrait.test(Animal a) have, and why?
boolean, because the test() method in CheckTrait is declared to return a boolean.
73
What is wrong with this lambda expression, and how would you fix it?
It's missing braces for multiple statements. The correct version is: java a -> { System.out.println(a); return a.canHop(); }
74
Why does this lambda expression fail to compile?
The return keyword is invalid in an expression-bodied lambda. Either remove return or use a block-bodied lambda: java a -> a.canHop() // Correct (expression body) // OR a -> { return a.canHop(); } // Correct (block body)
75
In a lambda expression, when are braces {} required?
Braces are required when the lambda body contains multiple statements or uses the return keyword.
76
What is the key difference between these two valid lambda expressions?
The first uses an expression body (no braces, implicit return), while the second uses a block body (explicit return required).
77
What is wrong with the following lambda expression syntax, and how would you correct it?
The semicolon after a.canHop() is incorrect because it's a single-expression lambda body. The correct form is: java a -> a.canHop()
78
In lambda expressions, when are curly braces {} required in the body?
Curly braces are required when the lambda body contains multiple statements or requires an explicit return statement (block body).
79
What are two ways to declare parameter types in a lambda expression?
Explicitly: (Animal a) -> a.canHop() Implicitly (type inferred): a -> a.canHop()
80
Why don’t single-expression lambda bodies need a return statement?
The result of the single expression is automatically returned (expression body).
81
What does Java infer in a lambda expression if parameter types are omitted?
Java infers the parameter types from the functional interface’s abstract method signature.
82
Which of these lambda expressions is invalid, and why?
The second is invalid because a block-bodied lambda must use return if the functional interface expects a value.
83
What are two key syntax differences between expression-bodied and block-bodied lambdas?
Expression bodies: No braces/semicolon (e.g., a -> a.canHop()). Block bodies: Requires braces, semicolons, and explicit return if non-void (e.g., a -> { return a.canHop(); }).
84
How does lambda syntax flexibility improve code readability?
Optional parentheses/braces reduce boilerplate, and type inference minimizes redundancy.
85
What is the correct syntax for a lambda expression with zero parameters that returns true?
java () -> true
86
What are two valid ways to write a lambda expression for a single parameter where the type is inferred?
java a -> a.canHop() x -> x.startsWith("test")
87
How would you write a lambda expression for a single parameter with an explicit Animal type that checks if it can hop?
java (Animal a) -> a.canHop()
88
What is the correct syntax for a lambda expression with multiple parameters that checks if one animal can hop and another can swim?
java (a, b) -> a.canHop() && b.canSwim()
89
How would you convert this single-expression lambda into a block-bodied lambda?
java a -> { return a.canHop(); }
90
What is the syntax for a valid lambda expression with an empty body that takes a String parameter?
java s -> {}
91
What is wrong with this lambda expression and how would you fix it?
Missing parentheses for multiple parameters. Correct version: java (a, b) -> a.startsWith(b)
92
What would be the equivalent block-bodied lambda for this expression?
java (x,y) -> { return x.equals(y); }
93
Which of these is NOT a valid lambda expression in Java and why?
2 is invalid because single-expression lambdas shouldn't use return without braces. Correct form would be either a -> a or a -> { return a; }
94
What is wrong with this lambda expression and how would you fix it?
It's missing parentheses for multiple parameters. Correct version: java (x, y) -> x.startsWith("fish")
95
Why does this lambda expression with block body fail to compile?
It's missing a return statement when a boolean needs to be returned. Correct version: java x -> { return x.startsWith("came"); }
96
What syntax error is present in this lambda expression and how would you correct it?
It's missing a semicolon in the block body. Correct version: java x -> { return x.startsWith("giraffe"); }
97
What is the problem with this typed parameter lambda expression and how would you fix it?
It's missing parentheses for the typed single parameter. Correct version: java (String x) -> x.endsWith("eagle")
98
Which of these lambda expressions is valid Java syntax?
java (String x) -> x.endsWith("eagle") The others shown in the examples would all produce compilation errors due to missing parentheses, return statements, or semicolons.
99
What is the correct lambda syntax for a zero-parameter expression body that returns "Hello"? Include the code.
java () -> "Hello"
100
Which lambda syntax is invalid for a single inferred-type parameter?
None are invalid - all are valid syntax (parentheses optional for single inferred parameter).
101
What is wrong with this lambda expression?
Mixed parameter types - either all parameters must be explicitly typed or all must use type inference.
102
What is the difference between these two lambda expressions?
The first uses a block body (requires return/semicolon), the second uses an expression body (no return/semicolon needed).
103
Which lambda body type requires semicolons for statements? Include an example.
Block body requires semicolons: java (x) -> { int y = x * 2; return y + 1; }
104
What is missing from this block body lambda that should return a value?
The return statement: java (a, b) -> { int sum = a + b; return sum; }
105
Why does this lambda fail to compile?
Block body with multiple expressions must have explicit return if returning a value, or be void-compatible.
106
Which lambda correctly implements Function with explicit types?
All are correct - the first two use expression bodies, the third uses a block body with explicit return.
107
What does the lambda expression () -> true represent, and which functional interface could it implement?
It's a no-argument lambda that always returns true. It could implement Predicate (as test()), BooleanSupplier, or any functional interface with a method that takes no arguments and returns a boolean.
108
Write a lambda expression that takes a String and returns whether it is empty, matching the Predicate interface.
java s -> s.isEmpty()
109
Which functional interface would the lambda (String str) -> str.length() > 5 be compatible with, and what does it do?
It implements Predicate, testing if the input String's length is greater than 5.
110
What does this lambda expression do, and what functional interface(s) could it implement?
It takes two objects (likely animals), checks if either a can hop OR b can swim, and returns a boolean. Could implement BiPredicate or a custom functional interface with two parameters and boolean return.
111
Convert this lambda into a method reference if possible:
Cannot be converted to a method reference because multiplication is an operation, not a method call.
112
What does this lambda expression do, and which standard functional interface does it match?
It takes an Integer and converts it to a String. Matches Function.
113
Write a lambda that concatenates the species of two animal objects (assuming they have a species() method).
java (a, b) -> a.species() + b.species()
114
Which functional interface does this lambda implement, and what is its output?
Implements Runnable. Output: Prints "Hello" to standard output when run.
115
Identify the error in this lambda if used for Predicate:
Missing return statement. Correct version: java str -> { return str.isEmpty(); }
116
What is the error in this lambda expression that should return a boolean?
It's missing the return keyword. The correct version should be: java Predicate p = s -> { return s.isEmpty(); };
117
Identify the syntax error in this BiPredicate lambda declaration:
Missing parentheses around parameters. Correct version: java BiPredicate bp = (s1, s2) -> s1.equals(s2);
118
Why is this BiFunction lambda invalid while the similar one is valid?
It mixes explicit (String s) and inferred (i) parameter types. Either all must be explicit or all inferred.
119
What does this valid lambda expression represent and why is it special?
It's an empty lambda that represents a no-op implementation of the Runnable interface's run() method.
120
In lambda parameter naming, which of these rules is correct?
All are correct - lambda parameter names can be any valid Java identifier and don't need to match the interface's parameter names.
121
What type of lambda expression would you use to implement a Predicate that checks if a string is empty?
java Predicate isEmpty = s -> s.isEmpty(); // or Predicate isEmpty = (String s) -> s.isEmpty();
122
What is wrong with this lambda expression that uses a block body but forgets to include a return statement?
It's missing the required return statement. The correct version should be: java Predicate p = s -> { return s.isEmpty(); };
123
Why does this lambda expression with mixed parameter typing fail to compile?
It mixes explicit (String s) and inferred types (i). Both parameters must be either explicitly typed or inferred: java (String s, Integer i) -> s.length() > i // OR (s, i) -> s.length() > i
124
What are two correct ways to rewrite this invalid lambda expression that uses braces without returning a value?
Either remove braces for expression body or add return statement: java Function f = s -> s.length(); // OR Function f = s -> { return s.length(); };
125
What are three key benefits of understanding lambda syntax variations in Java?
1) Write more concise, readable code 2) Quickly identify and fix lambda-related compilation errors 3) Choose the most appropriate form for each situation
126
In lambda expressions, when is the return keyword mandatory versus optional?
Return is mandatory in block bodies ({ }) when returning a value, and optional in expression bodies (single statement without braces).
127
What compilation error would occur with this lambda expression and why?
It would fail because Consumer's functional method returns void, but the lambda attempts to return a String. Either remove the return or change to Function.
128
Why does the following code fail to compile?
It fails because var cannot be used with lambda expressions since lambdas require a target type (functional interface) for type inference, and var has no type context.
129
What are two valid ways to declare a lambda expression that checks if an Animal can hop?
Explicit type declaration: java CheckTrait valid = (Animal a) -> a.canHop(); Providing context where Java can infer the type: java someMethodThatExpectsCheckTrait(a -> a.canHop());
130
What is the key requirement for Java to properly interpret a lambda expression?
The lambda must have a target type (functional interface) that provides context for type inference.
131
In the context of lambda expressions, why can't the compiler determine the type when using var?
Because var relies on the right-hand side expression for type inference, but lambdas themselves don't have an intrinsic type - they must be assigned to a functional interface.
132
What type of interface must be used as the target type for a lambda expression to be valid?
A functional interface (an interface with exactly one abstract method).
133
What is the SAM rule for functional interfaces in Java?
The SAM (Single Abstract Method) rule states that a functional interface must contain exactly one abstract method.
134
What is the purpose of the @FunctionalInterface annotation in Java? (Provide two key reasons)
1) Enforces functional interface rules at compile time, 2) Documents that the interface is meant for lambdas.
135
Analyze this code. Will it compile? Why or why not?
Yes, it will compile because it contains exactly one abstract method (sprint) and satisfies the functional interface requirements.
136
Identify the compilation error in this code:
The code won't compile because the interface has two abstract methods (move and rest), violating the SAM rule for functional interfaces.
137
Which of these interface declarations is a valid functional interface?
Option A (Runner) is a valid functional interface because it has exactly one abstract method (run). Option B has two abstract methods.
138
What would happen if you removed the @FunctionalInterface annotation from a valid functional interface?
The interface would still be a valid functional interface (usable with lambdas), but it would lose the compile-time validation and documentation benefits.
139
True or False: A functional interface can contain multiple default or static methods as long as it has only one abstract method.
True. Functional interfaces can have any number of default or static methods, but only one abstract method.
140
In the context of functional interfaces, what does SAM stand for?
SAM stands for Single Abstract Method.
141
What makes the Sleep interface a valid functional interface despite having multiple methods? Include the code in your analysis.
The Sleep interface is valid because it contains only one abstract method (fallAsleep()). The other methods (snore() and getZZZ()) are private and default methods, which don't count toward the abstract method limit. java public interface Sleep { private void snore() {} // Private method default int getZZZ() { // Default method return 1; } void fallAsleep(); // Single abstract method }
142
Why is Dash extends Sprint a valid functional interface declaration?
Because it inherits only one abstract method (sprint()) from its parent interface, maintaining the single-abstract-method requirement. java public interface Dash extends Sprint {} // Inherits sprint()
143
Identify why the Skip interface is NOT a valid functional interface. Include the code.
It has two abstract methods (sprint() inherited from Sprint and skip()), violating the single-abstract-method rule. java public interface Skip extends Sprint { void skip(); // Now has two abstract methods (sprint() + skip()) }
144
Why would the Climb interface be invalid as a functional interface if it doesn't inherit any methods? Include the code.
It contains zero abstract methods, failing the functional interface requirement of having exactly one abstract method. java public interface Climb {} // No abstract methods
145
In the Sleep interface code, what is the purpose of the private void snore() {} declaration?
It declares a private helper method that can only be used within the interface's default methods, not counting toward the abstract method total.
146
What would happen if you added public void wakeUp(); to the Sleep interface?
It would become invalid as a functional interface because it would have two abstract methods (fallAsleep() and wakeUp()).
147
What are the three types of methods in a functional interface that do NOT count toward the single abstract method requirement?
1) Methods from Object class (like toString(), equals()), 2) Default methods, 3) Private methods.
148
Given this functional interface declaration, identify if it's valid and why:
Valid. The equals() method is from Object class and doesn't count, leaving only one abstract method (process()).
149
What is the single abstract method in the Predicate functional interface and what does it return?
boolean test(T t) - it takes one parameter of type T and returns a boolean.
150
What will this code output?
3 (the length of the string "OCA")
151
Why does this lambda expression compile successfully with the Consumer interface?
Because the lambda matches the Consumer's single abstract method signature void accept(T t).
152
Identify the error in this functional interface declaration:
There is no error. It's valid because it has exactly one abstract method (calculate()), while toString() and equals() are from Object class and printResult() is a default method.
153
What built-in functional interface would you use for a lambda that takes a String and returns its length as an Integer?
Function
154
What will this code output?
true (Math.random() always returns a double between 0.0 and 1.0)
155
Given this code, what is the correct way to call the process method?
Example call: java StringTransformer repeater = (s, n) -> s.repeat(n); System.out.println(repeater.process("Hi", 3)); // Output: "HiHiHi"
156
What does the following Predicate lambda expression evaluate to, and why?
It evaluates to false because the string "short" has only 5 characters, which is not greater than 10.
157
What will be printed by this Function lambda expression and why?
It will print "ff" because the Function converts the integer 255 to its hexadecimal string representation.
158
Why is the following interface NOT a valid functional interface despite having only one declared abstract method?
It's invalid because while it declares only one abstract method (doSomething()), the equals() method is also abstract (inherited from Object), making two abstract methods total.
159
What is wrong with the following interface declaration that attempts to extend Runnable?
It's invalid because it declares two abstract methods (additionalMethod() and the inherited run() from Runnable), violating the single abstract method requirement for functional interfaces.
160
True or False: The @FunctionalInterface annotation is mandatory for an interface to be considered functional in Java.
False. The annotation is optional and serves only as documentation. Many built-in functional interfaces (like Runnable) don't use it.
161
What is the purpose of the @FunctionalInterface annotation in Java? Provide a code example.
The @FunctionalInterface annotation ensures an interface has exactly one abstract method, making it suitable for lambdas. Example: java @FunctionalInterface interface Greeter { void greet(String name); // Single abstract method }
162
When should you use the @FunctionalInterface annotation? (Select two)
1) When designing an interface specifically for lambdas. 2) When you want to ensure it stays functional during future maintenance.
163
Given this code, which line would cause a compilation error?
The interface declaration would fail because @FunctionalInterface requires exactly one abstract method, but there are two (calculate and printResult).
164
When should you prefer using Java's built-in functional interfaces like Predicate or Function?
When they match your needs and when you want better interoperability with existing Java APIs.
165
Name three scenarios when you should create a custom functional interface instead of using built-in ones.
1) When you need a more domain-specific name, 2) When built-in interfaces don't fit your needs, 3) When you need to add additional default/static methods.
166
Which built-in functional interface would be most appropriate for a boolean test condition?
java.util.function.Predicate
167
What will happen if you add a second abstract method to an interface marked with @FunctionalInterface?
The code will fail to compile because @FunctionalInterface enforces the single-abstract-method rule.
168
What is the Single Abstract Method (SAM) rule for functional interfaces in Java?
A functional interface must contain exactly one abstract method. Default, static, and private methods don't count toward this total.
169
Which methods in the following interface count toward the SAM rule?
Only reach() counts toward the SAM rule. The default and static methods don't count.
170
Why is the following interface considered a valid functional interface despite having multiple method declarations?
It's valid because toString(), equals(), and hashCode() are Object methods and don't count toward the SAM rule, leaving only dive() as the abstract method.
171
What makes this interface a valid functional interface?
It's valid because it inherits only one abstract method (sprint()) from the parent interface, satisfying the SAM rule.
172
Which of these methods in a functional interface would count toward the abstract method total?
Only doWork() counts toward the abstract method total. The private and static methods don't count, and toString() is an Object method.
173
How many abstract methods does this interface have for SAM rule purposes?
It has 1 abstract method (move()) for SAM purposes. equals() is an Object method and doesn't count, and stop() is a default method.
174
Why is the Skip interface invalid as a functional interface in Java?
It's invalid because it has two abstract methods (sprint() inherited from Sprint and skip()), violating the single abstract method requirement for functional interfaces. java public interface Skip extends Sprint { void skip(); // Now has sprint() + skip() }
175
What makes the Sleep interface invalid as a functional interface?
It's invalid because it has zero abstract methods (only contains a private method and default method), while functional interfaces require exactly one abstract method. java public interface Sleep { private void snore() {} default int getZZZ() { return 1; } }
176
Why doesn't the Soar interface qualify as a valid functional interface despite having an abstract method?
It's invalid because the only abstract method (toString()) is inherited from Object, which doesn't count toward the functional interface requirement. java public interface Soar { abstract String toString(); // Only method, but from Object }
177
How many abstract methods that count toward functional interface requirements does the Hibernate interface have, and why is it invalid?
It has two counting abstract methods (equals(Hibernate) and rest()), making it invalid as functional interfaces can only have one. The Object methods (toString() and hashCode()) don't count. java public interface Hibernate { String toString(); // Doesn't count (Object) public boolean equals(Hibernate o); // Different signature! public abstract int hashCode(); // Doesn't count (Object) public void rest(); // Counts }
178
In the Hibernate interface, why doesn't the equals(Hibernate) method count as an Object method?
Because it has a different signature (Hibernate parameter) than Object's equals(Object), so it counts as a new abstract method. java public boolean equals(Hibernate o); // Different signature!
179
What are the three Object methods that are always available to all Java classes (shown in code format)?
java public String toString() public boolean equals(Object) public int hashCode()
180
Why don't Object methods count against the "single abstract method" rule in functional interfaces?
Because they are always available to all classes and don't need to be separately implemented.
181
What makes the following method declaration count as an abstract method in an interface (instead of being treated as an Object method override)?
It counts as abstract because: It doesn't override Object's equals() The parameter type (Hibernate) differs from Object's equals(Object) It's treated as a new abstract method
182
When designing functional interfaces, what is safe to do with Object methods without affecting functional status?
You can safely redeclare Object methods (like toString(), equals(), hashCode()) without them counting as additional abstract methods.
183
What three checks should you perform when evaluating if an interface is functional?
Check for: Default/static/private methods Object method overrides Subtle signature differences in method declarations
184
What will happen if you declare the following method in a functional interface?
It will count as an additional abstract method (making the interface non-functional) because the parameter type (String) differs from Object's equals(Object).
185
Identify why the following interface is still functional despite having multiple method declarations:
It's functional because toString() and equals(Object) are Object method overrides, leaving only process() as the single abstract method.
186
Given the following interface, why is it NOT a functional interface despite having only one declared method?
It's not functional because it has two abstract methods - perform() and equals(Object) (which doesn't override Object's equals). Object methods only don't count if they properly override.
187
What makes interface B non-functional in this code, even though each interface individually has one abstract method?
Interface B has two abstract methods (inherits foo() from A and declares bar()), violating the single abstract method requirement for functional interfaces.
188
Identify the error in this functional interface declaration that would cause a compilation error:
There is no error - this is a valid functional interface because it has exactly one abstract method (calculate) and one default method, which doesn't count against the functional interface requirement.
189
What is the purpose of the @FunctionalInterface annotation in Java? (Select all that apply)
1) Makes intent clear 2) Provides compiler verification 3) Prevents accidental breaking of the functional contract by adding extra abstract methods.
190
How many abstract methods does interface C contain, and is it a functional interface?
It contains 2 abstract methods (equals(C) and doWork()), making it non-functional. The equals(C) method doesn't override Object's equals(Object) so it counts as abstract.
191
Which of these interface declarations is a valid functional interface?
Both Option 1 (X) and Option 2 (Y) are valid functional interfaces. Option 1 has one abstract method. Option 2 has only Object method overrides which don't count. Option 3 (Z) is invalid as it has two abstract methods.
192
What critical check should you perform when determining if an interface is functional?
Verify: 1) Exact count of abstract methods (must be 1) 2) Whether any methods are Object method overrides 3) That no methods have non-standard signatures that make them additional abstract methods.
193
What is the purpose of method references in Java?
Method references provide a shorthand notation for lambda expressions that simply call an existing method, making code more concise and readable.
194
What operator is used for method references in Java?
The double colon operator :: is used for method references.
195
How many distinct types of method references exist in Java?
There are four distinct types of method references in Java.
196
What is required for method references to be used, similar to lambda expressions?
Method references require a functional interface context, just like lambda expressions.
197
Given the code Consumer printer = System.out::println;, what does this method reference do?
This method reference is equivalent to the lambda (String s) -> System.out.println(s) and prints the input string to standard output.
198
What is the behavioral relationship between method references and lambda expressions at runtime?
Method references are behaviorally equivalent to their corresponding lambda expressions at runtime.
199
Which of the following is NOT a characteristic of method references?
2) Use the -> operator (Method references use the :: operator, not ->)
200
In the context of method references, what does "behaviorally equivalent to lambdas" mean?
It means method references and their corresponding lambda expressions perform the same operation and can be used interchangeably in functional interface implementations.
201
Given the functional interface LearnToSpeak with method void speak(String), which of these correctly replaces the lambda s -> System.out.println(s) with a method reference?
A) LearnToSpeak learner = System.out::println;
202
What makes System.out::println a valid method reference replacement for s -> System.out.println(s) when assigned to a LearnToSpeak variable?
Because System.out.println(String) matches the functional interface's void speak(String) method signature.
203
Which type of method reference is Integer::parseInt when used in this assignment?
It's a static method reference (ClassName::staticMethodName).
204
What is the equivalent lambda expression for this method reference?
() -> str.toUpperCase()
205
Given the following code, what type of method reference is being used?
Instance method on a particular object (objectReference::instanceMethodName).
206
Which functional interface would correctly match the method reference String::length when used in this context?
Function (since length() takes no parameters and returns int)
207
What is wrong with this method reference attempt?
The syntax is incorrect - it should be System.out::println (no dot between System and out).
208
Which of these is NOT a valid type of method reference in Java?
E) All are valid (All four types are valid method references in Java)
209
What is the syntax for an instance method reference on a runtime parameter in Java?
ClassName::instanceMethodName
210
Given the code Function upper = String::toUpperCase;, what is the equivalent lambda expression?
s -> s.toUpperCase()
211
What does String::toUpperCase represent in Java method references?
It is an instance method reference that calls toUpperCase() on a String object at runtime.
212
What is the syntax for a constructor reference in Java?
ClassName::new
213
Given the code Supplier> listSupplier = ArrayList::new;, what is the equivalent lambda expression?
() -> new ArrayList<>()
214
What does ArrayList::new represent in Java method references?
It is a constructor reference that creates a new ArrayList object when invoked.
215
In the context of method references, what type of functional interface would ArrayList::new typically be assigned to?
A Supplier functional interface (e.g., Supplier>).
216
What is the method reference equivalent to the lambda (a, b) -> Math.max(a, b)?
Math::max
217
Given the lambda s -> str.contains(s), what is its corresponding method reference if str is an existing String object?
str::contains
218
What does the method reference String::isEmpty represent, and what is its equivalent lambda expression?
It calls isEmpty() on a String parameter. The equivalent lambda is s -> s.isEmpty().
219
Which method reference is equivalent to the lambda () -> new ArrayList<>()?
ArrayList::new
220
Given the following code, which method reference would replace the lambda correctly?
System.out::println
221
What is the difference between String::length (method reference) and s -> s.length() (lambda)?
Both call length() on a String parameter, but the method reference (String::length) is a more concise syntax.
222
If you see the method reference obj::someMethod, what must obj represent for this to be valid?
obj must be an existing instance of an object where someMethod is an instance method.
223
What is the equivalent lambda for the constructor method reference HashSet::new?
() -> new HashSet<>()
224
In the method reference Math::pow, how many parameters does the corresponding lambda require?
Two parameters (e.g., (a, b) -> Math.pow(a, b)).
225
What does the method reference this::doSomething refer to?
It refers to an instance method doSomething in the current class.
226
What is the preferred way to write a lambda expression when it only calls an existing method like System.out.println()?
Use a method reference instead: list.forEach(System.out::println); is preferred over list.forEach(x -> System.out.println(x));
227
Why would you use String::toUpperCase as a method reference in a stream operation?
For clearer intent and readability: names.stream().map(String::toUpperCase)... directly shows the transformation purpose.
228
What type of method reference would you use with a constructor, as shown in this code?
This is a reference to a static method (LocalDate.now()), used here to create a Supplier functional interface.
229
Why can't you use a method reference in this case?
Because it requires modifying parameters (both trim() and toLowerCase() operations), which isn't possible with a single method reference.
230
When must you use a lambda expression instead of a method reference? Provide a code example.
When the logic requires multi-step operations: java list.forEach(x -> { String processed = process(x); System.out.println(processed); });
231
What type of method reference is System.out::println and why is it preferred over a lambda here?
It's an instance method reference of a specific object (System.out), preferred because it's more concise and directly expresses the simple operation.
232
Identify the error if you tried to replace this lambda with a method reference:
You can't directly use a method reference here because the operation involves a comparison (> 5), not just a method call.
233
What type of method reference is String::valueOf and why?
String::valueOf is a static method reference because valueOf is a static method of the String class that can be called without an instance.
234
What type of method reference is String::length and why?
String::length is an instance method reference because length() is an instance method that operates on a String object.
235
What is wrong with this method reference assignment: BiFunction wrong = String::toUpperCase;?
The method reference is invalid because toUpperCase() takes no parameters, but BiFunction requires a method that accepts two parameters (String and Integer).
236
Why does Object obj = String::new; fail to compile?
It fails because Object is not a functional interface, and method references can only be used with functional interfaces (interfaces with exactly one abstract method).
237
Given the method reference String::valueOf, what would be the correct functional interface to assign it to?
It could be assigned to Function since String.valueOf(Object) takes one parameter and returns a String.
238
What parameter count does the method String::length implicitly expect when used as a method reference?
It expects one parameter - the String instance it will operate on (even though length() itself takes no parameters when called normally).
239
What does the following code do, and what type of method reference is String::compareToIgnoreCase?
It sorts the names list case-insensitively. String::compareToIgnoreCase is an instance method reference of a particular object (the first parameter becomes the target object).
240
In the code below, what does Color::new represent and what type of method reference is it?
Color::new is a constructor reference that creates new Color objects from each string. It's a constructor method reference.
241
What will be the result of this code snippet and what type of method reference is String::isEmpty?
It returns 2 (count of empty strings). String::isEmpty is an instance method reference.
242
What are the four flavors of method references in Java?
1) Static method reference, 2) Instance method reference of a particular object, 3) Instance method reference of an arbitrary object of a particular type, 4) Constructor reference.
243
True or False: All lambda expressions can be converted to method references.
False. Only lambdas that directly call existing methods can be converted to method references.
244
What is the primary advantage of using method references over lambda expressions?
Method references make the code more concise and readable when the lambda simply calls an existing method.
245
In the context of method references, what does System.out::println represent?
It's an instance method reference of a particular object (out), equivalent to x -> System.out.println(x).
246
What would be the lambda equivalent of the method reference Integer::parseInt?
s -> Integer.parseInt(s)
247
Which of these is NOT a valid method reference type?
d) Destructor (Java doesn't have destructor method references)
248
What is the correct syntax for referencing a static method using method references in Java?
The syntax is ClassName::methodName.
249
In the given code, what does Math::round reference and what functional interface does it implement?
Math::round references the static round() method from the Math class and implements the Converter functional interface which has a matching method signature.
250
What is the lambda expression equivalent to the method reference Math::round in the given example?
The equivalent lambda expression is: java Converter lambda = x -> Math.round(x);
251
What will be the output of the following code using the method reference?
The output will be 100 because Math.round(100.1) returns 100.
252
How does Java handle method overloading when using method references to static methods?
Java infers the correct overloaded method based on the context and the functional interface's method signature.
253
What is the key characteristic of static method references regarding parameter types?
Java infers the parameter types from the functional interface's method signature.
254
Given the following code, which line demonstrates a static method reference?
The line Converter methodRef = Math::round; demonstrates a static method reference.
255
Given the Math.round() method is overloaded for float and double parameters, and a Converter interface specifies a double parameter, which version of Math.round() will Java select when used in this context?
Java will select the Math.round(double) version because the functional interface specifies a double parameter.
256
What is the key factor that determines which overloaded method version is selected by the Java compiler?
The compiler resolves overloaded methods by matching the parameter types specified in the method call to the available method signatures.
257
What happens if there are multiple matching overloaded methods for a method call?
If the method call is ambiguous (has multiple matches), the compiler will generate a compilation error.
258
What must match between a method reference and its functional interface besides parameter types?
The return type of the method reference must also match the return type specified in the functional interface.
259
Analyze the following code and explain how the instance method reference works:
The method reference str::startsWith creates a functional interface implementation where str is the fixed object that will receive the startsWith() call, and the String parameter passed to beginningCheck() will be used as the prefix argument.
260
What will be the output of this code and why?
The output will be false because it checks if "Zoo" starts with "A", which it does not.
261
What is the equivalent lambda expression for the method reference str::startsWith in this context?
The equivalent lambda is s -> str.startsWith(s) where s is the parameter passed to the functional interface method.
262
When using an instance method reference with objectReference::methodName, at what time is the object fixed?
The object is fixed at the time the method reference is created, not at invocation time.
263
When are parameters passed when using an instance method reference?
Parameters (if any) are passed at the time the functional interface method is invoked, not when the method reference is created.
264
What is the output of the following code?
The output is true because str.isEmpty() returns true for an empty string.
265
What is the lambda expression equivalent to this method reference?
The equivalent lambda expression is: java StringChecker lambda = () -> str.isEmpty();
266
Why does this method reference fail to compile?
It fails because startsWith() requires a String parameter, but the StringChecker functional interface's check() method takes no parameters.
267
Why does this method reference fail to compile?
Method references cannot hardcode parameters. The parameter must be passed through the functional interface's method.
268
Given the interface:
Only the lambda version works: java StringChecker lambda = () -> str.startsWith("Zoo"); The method reference versions fail due to parameter requirements.
269
What is the key difference between these two functional interface implementations?
Both are functionally equivalent, but one uses a method reference while the other uses a lambda expression. The method reference is more concise.
270
For instance methods with parameters (like startsWith), what is the correct lambda equivalent of this method reference?
The lambda equivalent would be: java SomeInterface lambda = s -> str.startsWith(s); (Assuming SomeInterface has a method that takes one String parameter)
271
What is the key reason why a lambda expression with a hardcoded parameter like s -> "Zoo".startsWith(s) cannot be converted to a method reference?
Method references cannot hardcode parameters; they must work with the functional interface's method signature where parameters are passed dynamically.
272
Given the code snippet:
["Zebra"] (only elements starting with "Z")
273
What does the following method reference expression do?
It creates a Predicate that tests whether a given String is empty, equivalent to s -> s.isEmpty().
274
Identify the sorting behavior in this code:
It sorts the list alphabetically ignoring case, resulting in ["apple", "banana", "cherry"].
275
Why does this code fail to compile?
It's ambiguous because multiple Integer.valueOf() methods match (valueOf(String) and valueOf(int)), making the method reference unclear.
276
What is wrong with this method reference assignment?
String::startsWith requires two parameters (the string and prefix), but Predicate's test() method only provides one parameter.
277
Which functional interface would correctly match the String::startsWith method reference?
BiPredicate because startsWith requires two String parameters (the implicit 'this' and the prefix).
278
In the context of method references, what is the key difference between these two expressions?
Takes one parameter (tests if "Z" starts with the argument) Takes two parameters (tests if first string starts with second string)
279
What is wrong with the following Java code that attempts to create a Function using a method reference with a fixed parameter?
The code is invalid because method references cannot pass fixed parameters. startsWith requires a String argument, but "prefix" is hardcoded, making the method reference incompatible with Function.
280
When should you prefer using method references over lambdas in Java? (Select all that apply)
You should prefer method references when: The lambda simply calls an existing method. It improves readability. The method signature matches the functional interface.
281
In which scenarios should you use lambdas instead of method references in Java? (Select all that apply)
Prefer lambdas when: You need to pass fixed parameters. The operation is more complex than a single method call. Method references would be ambiguous.
282
True or False: All method references can be written as lambdas, but not all lambdas can be written as method references.
True. Method references are syntactic sugar for lambdas calling existing methods, but lambdas with custom logic or fixed parameters cannot be converted.
283
What determines whether a method reference is valid for a given functional interface in Java?
The method signature (return type, parameters) must match the functional interface's abstract method. The compiler checks compatibility.
284
What will the Java compiler do if you attempt to use an invalid method reference?
The compiler will report an error, as the conversion is checked at compile-time for type compatibility.
285
What is the correct syntax for a static method reference in Java, and what would be the equivalent lambda expression for Converter methodRef = Math::round;?
Syntax: ClassName::staticMethodName. Equivalent lambda: x -> Math.round(x)
286
Given the code String str = "Hello"; StringChecker methodRef = str::isEmpty;, what type of method reference is this and what is its equivalent lambda expression?
This is an instance method on a specific object. Equivalent lambda: () -> str.isEmpty()
287
Identify the type of method reference and its lambda equivalent in: StringParameterChecker methodRef = String::isEmpty;
This is an instance method on a parameter. Equivalent lambda: s -> s.isEmpty()
288
What is the syntax for constructor references in Java, and what lambda expression is equivalent to EmptyStringCreator methodRef = String::new;?
Syntax: ClassName::new. Equivalent lambda: () -> new String()
289
Which of the four method reference types would you use to reference Math.sqrt() and what would the syntax be?
Static method reference. Syntax: Math::sqrt
290
Given the code List names = Arrays.asList("A","B"); names.forEach(System.out::println);, what type of method reference is System.out::println?
Instance method on a specific object (System.out is the specific object)
291
What would be the lambda equivalent of the constructor reference ArrayList::new when assigned to a Supplier>?
() -> new ArrayList()
292
In the method reference String::length, why is this considered an instance method on parameter rather than a static method reference?
Because length() is an instance method that will be called on the String parameter passed to the functional interface
293
Given this interface and method reference:
The equivalent lambda expression is s -> s.isEmpty()
294
In the method reference String::isEmpty used with StringParameterChecker, how does Java determine which String instance to call isEmpty() on?
Java uses the single String parameter from the functional interface's check method as the instance to call isEmpty() on.
295
Given this interface and method reference:
The equivalent lambda expression is (s, p) -> s.startsWith(p)
296
For the method reference String::startsWith used with StringTwoParameterChecker, how are the interface's parameters mapped to the instance method call?
The first parameter becomes the String instance, and the second parameter becomes the argument passed to startsWith().
297
What is a critical rule about parameter order when using instance method references on parameters?
The instance parameter must always come first in the functional interface's parameter list.
298
Given this code:
checker.test("hello", "ell") would return true.
299
What does this constructor reference create?
It creates a new empty String using String's no-arg constructor, equivalent to new String().
300
Given this interface and constructor reference, which String constructor will be invoked?
The String constructor that takes a String parameter (String(String original)), equivalent to s -> new String(s).
301
How does Java determine which constructor to use when the same syntax String::new appears in different contexts?
Java infers the constructor based on the functional interface's method signature - the parameter types and return type.
302
What is the equivalent lambda expression for this constructor reference?
() -> new String()
303
What is the equivalent lambda expression for this constructor reference?
s -> new String(s)
304
What will be the result of executing this code?
true (creates an empty String which has isEmpty() = true)
305
Why can String::new refer to different constructors in different contexts?
Because constructor references are poly expressions - their meaning depends on the target type (functional interface) they're assigned to.
306
Why can't the lambda () -> str.startsWith("Zoo") be converted to a method reference in Java?
Because method references cannot hardcode parameters ("Zoo") and require both the instance (str) and parameter to be variable.
307
What is the method reference equivalent of the lambda x -> Math.round(x)?
Math::round
308
Given the code str::contains, write its lambda equivalent.
s -> str.contains(s)
309
What is the correct method reference for the lambda s -> s.toUpperCase()?
String::toUpperCase
310
Convert the two-parameter lambda (s,p) -> s.startsWith(p) to a method reference.
String::startsWith
311
What is the method reference equivalent of the no-arg constructor lambda () -> new ArrayList<>()?
ArrayList::new
312
Given the parameterized constructor lambda s -> new String(s), write its method reference equivalent.
String::new
313
What makes the method reference Integer::parseInt ambiguous in the context of the Ambiguous interface?
It's unclear whether it refers to Integer.parseInt(String) (radix 10) or Integer.parseInt(String, int) (with radix parameter).
314
In the incorrect BiFunction example (p,s) -> s.startsWith(p), what is wrong with the parameter order?
The parameters are reversed from the expected (s,p) -> s.startsWith(p) order that String::startsWith would use.
315
Why does TriFunction fixed = String::substring(1,4) result in a compile error?
Method references cannot bind specific parameters (1,4) - they must reference the method generically (String::substring).
316
What type of method reference is String::toUpperCase an example of?
An instance method on a parameter (the String parameter becomes the object the method is called on).
317
What is the key limitation shown when trying to create a method reference for () -> str.startsWith("Zoo")?
Method references cannot hardcode specific parameter values like "Zoo".
318
What are three scenarios where method references should be used in Java?
When the lambda only calls an existing method. When it makes the code more readable. When the method signature matches the functional interface.
319
In which cases should you prefer lambdas over method references in Java?
When you need to modify parameters before passing them. When the logic is more complex than a single method call. When method references would be ambiguous.
320
Given the following lambda expression, convert it to a method reference:
java Function f1 = String::length;
321
Given the following lambda expression, convert it to a method reference:
java Function f2 = String::trim;
322
Given the following lambda expression, convert it to a method reference:
java BiPredicate f3 = String::startsWith;
323
What are the four types of method references in Java, and what is the syntax for each?
Static: Class::staticMethod (e.g., Math::random) Instance on object: object::method (e.g., str::toUpperCase) Instance on parameter: Class::instanceMethod (e.g., String::length) Constructor: Class::new (e.g., ArrayList::new)
324
Given the code Supplier s1 = String::new;, what does this constructor reference represent and what is its lambda equivalent?
It represents a no-arg String constructor reference. Lambda equivalent: () -> new String()
325
Given the code Function s2 = String::new;, what does this constructor reference represent and what is its lambda equivalent?
It represents a String constructor that takes a String parameter. Lambda equivalent: s -> new String(s)
326
How does Java determine which constructor to use in a constructor reference?
Java infers which constructor to use based on the functional interface context (the expected parameter and return types).
327
In the BiFunction BiFunction f = String::substring;, what is the parameter order for the instance method reference?
The first parameter is the String object instance, and the second is the Integer parameter: (s,i) -> s.substring(i)
328
When must you use a lambda expression instead of a method reference? Provide two scenarios.
When you need to hardcode parameters (e.g., s -> s.startsWith("fixed")) When you need to perform operations before calling (e.g., s -> s.trim().length())
329
What is the method reference equivalent of the lambda () -> Math.random()?
Math::random
330
What is the method reference equivalent of the lambda () -> str.toUpperCase() (assuming str is a String object)?
str::toUpperCase
331
What is the method reference equivalent of the lambda s -> s.length()?
String::length
332
What is the method reference equivalent of the lambda () -> new ArrayList<>()?
ArrayList::new
333
Given the code Function f = String::length;, what would f.apply("hello") return?
It would return 5 (the length of the string "hello").
334
What is the purpose of the Supplier functional interface in Java, and what does the following code do?
Supplier is used for factory patterns and lazy generation. The code creates a Supplier that provides new ArrayList instances when get() is called, then uses it to create a new list.
335
Which functional interface would you use to represent an operation that takes two arguments and returns a boolean, and what is its method name?
BiPredicate with method test(T,U).
336
What does this code demonstrate about functional interfaces and method references?
It shows how method references can implement functional interfaces, here using String::length to create a Function that gets string lengths.
337
Identify the functional interface that takes no arguments and returns a value, and name its single abstract method.
Supplier with method get().
338
What is the key difference between Function and UnaryOperator?
Function transforms input type T to output type R, while UnaryOperator transforms T to T (same input/output type).
339
Which functional interface would you use for a two-argument operation that produces a result of the same type as its inputs?
BinaryOperator.
340
What does this code do, and which functional interface is being used?
It creates a predicate to test if strings are empty using String::isEmpty, then tests it with an empty string (returning true). Uses Predicate.
341
Name the functional interface designed specifically for operations that accept a single argument and return no result.
Consumer.
342
What is the method signature of the functional interface BiFunction?
R apply(T t, U u).
343
Which functional interface would be most appropriate for implementing a string concatenation operation?
BinaryOperator (as it takes two strings and returns a string).
344
What is the purpose of specialized functional interfaces like IntSupplier, LongConsumer, and DoublePredicate in Java?
They avoid boxing overhead when working with primitive types by providing optimized versions of standard functional interfaces.
345
In the stream processing example:
filter uses Predicate, map uses Function, and forEach uses Consumer.
346
What would be the output of the following stream processing code?
ALICE\nCHARLIE
347
How would you rewrite the filter operation s -> s.startsWith("A") using a method reference?
It would need to be written as s -> s.startsWith("A") since method references can't be used directly with parameters in this case.
348
In the conditional logic example:
It evaluates the predicate (the lambda expression) on the given input string and returns a boolean.
349
What functional interface would you use to implement a factory pattern that creates new Connection objects, as shown in this code?
The Supplier functional interface, which represents a supplier of results.
350
What is the key advantage of using a Supplier for object creation as shown in the factory pattern example?
It provides lazy initialization, as the object is only created when get() is called.
351
Which functional interface would you use to implement a boolean test that could be used in an if statement?
The Predicate interface, which has a single abstract method test(T t) that returns a boolean.
352
In the stream processing example, what is the purpose of the map(String::toUpperCase) operation?
It transforms each string to uppercase using the Function interface, which takes a String input and returns a String output.
353
What is the error in this method reference declaration, and how would you fix it?
The error is that startsWith requires 2 parameters (String and prefix), so it can't be used with Predicate. The correct functional interface is: java BiPredicate correct = String::startsWith;
354
Why is this method reference invalid when assigned to a Consumer?
Because toUpperCase() returns a String, but Consumer requires a void return type. The correct functional interface is: java Function correct = String::toUpperCase;
355
What performance issue exists with this lambda expression, and how would you optimize it?
It causes unnecessary boxing/unboxing of primitive int. The optimized version uses IntUnaryOperator: java IntUnaryOperator square = x -> x * x;
356
Which functional interface should you use for a method reference to String.startsWith() that takes two String parameters?
BiPredicate because startsWith takes a String receiver and String prefix, and returns boolean.
357
What is wrong with assigning String::toUpperCase to a Consumer from a type compatibility perspective?
Consumer expects void accept(String t), but toUpperCase() returns String, making them incompatible types.
358
Why is IntUnaryOperator more efficient than Function for primitive integer operations?
IntUnaryOperator avoids boxing/unboxing overhead by working directly with primitive int types.
359
Which functional interface would you use for a lambda that takes no arguments but returns a value, and what is its key method?
Supplier with method get(). Example: java Supplier s = () -> "Hello";
360
What functional interface accepts one argument and returns no result, and what is its method name?
Consumer with method accept(T t). Example: java Consumer c = str -> System.out.println(str);
361
Given the code below, which functional interface matches this lambda, and what would it return for input 5?
Predicate (tests conditions), returns true for input 5. Method: test(T t)
362
Identify the functional interface and result type for this transformation lambda:
Function where T is String (input) and R is Integer (output). Method: apply(T t)
363
Which functional interface would you use for a lambda that takes two integers and returns their sum, and what is its method name?
IntBinaryOperator (subtype of Operator), method applyAsInt(int left, int right). Example: java IntBinaryOperator op = (a,b) -> a + b;
364
What is the key difference between Function and Operator functional interfaces?
Function transforms input to output of different types (e.g., String→Integer), while Operator operates on and returns the same type (e.g., Integer→Integer).
365
What is the purpose of the Supplier functional interface in Java, and what is its single abstract method?
The Supplier interface generates/supplies values without any input. Its single abstract method is T get().
366
Given this code using Supplier with a method reference, what will dateSupplier.get() return?
It will return the current date as a LocalDate object, equivalent to calling LocalDate.now().
367
How does this Supplier implementation using a constructor reference work?
It creates a Supplier that generates new StringBuilder instances when get() is called, equivalent to new StringBuilder().
368
What does this generic Supplier implementation create when get() is called?
It creates a new empty ArrayList when get() is invoked.
369
Identify three common use cases for the Supplier interface in Java.
1) Object creation/factory patterns, 2) Lazy initialization, 3) Value generation without inputs.
370
What is the purpose of the Consumer functional interface, and what is its single abstract method?
The Consumer interface performs operations on a single input without returning anything. Its method is void accept(T t).
371
What types of operations are Consumers typically used for in Java?
Consumers are typically used for side-effect operations like printing, saving data, or modifying state.
372
Given this Consumer example, what will be printed?
It will print "Hello OCA" followed by a new line to standard output.
373
How does the BiConsumer interface differ from the Consumer interface?
BiConsumer operates on two input parameters instead of one, using void accept(T t, U u) method.
374
What is the key characteristic that distinguishes Supplier from Consumer interfaces?
Supplier produces values (no input, returns T) while Consumer consumes values (takes T input, returns void).
375
What does the following Java code do?
It declares a Consumer using a method reference to System.out.println, then prints "Hello World" to the console when accept() is called.
376
How would you modify this code to print all elements of a List named names?
Use names.forEach(printer); to print each element (as shown in the Collection Processing example).
377
What is the output of this code and why?
Output: "TEST" - The lambda expression converts the input string to uppercase before printing.
378
Identify the functional interface used in this code snippet:
Consumer - forEach expects a Consumer that accepts a single input (each list element).
379
What is the difference between these two lines in terms of functionality?
Both produce identical results. The first uses a method reference, while the second uses an equivalent lambda expression.
380
What would happen if you tried to use this consumer with a null list?
It would throw a NullPointerException because you cannot invoke forEach on a null reference.
381
Which Java package must be imported to use the Consumer functional interface?
java.util.function.Consumer (part of java.util.function package).
382
Write a Consumer that prints a string with "Processed: " prefix. Use lambda syntax.
java Consumer prefixPrinter = s -> System.out.println("Processed: " + s);
383
What is the primary purpose of the BiConsumer functional interface in Java?
It performs operations on two input parameters (T and U) without returning any value (void).
384
What is the single abstract method (SAM) defined in the BiConsumer interface?
void accept(T t, U u).
385
Given the following code, what does mapPut.accept("Alice", 25) do?
It adds the key-value pair ("Alice", 25) to the HashMap using a BiConsumer that references map.put().
386
What will the following code print?
"Bob is 30 years old" followed by a newline.
387
Identify the output of this code snippet:
"Hello World " (with a trailing space).
388
How does BiConsumer differ from Consumer in terms of inputs and output?
BiConsumer takes two inputs (T and U) and returns void, while Consumer takes one input (T) and returns void.
389
Which functional interface would you use for a two-parameter operation that modifies a collection (e.g., Map.put())?
BiConsumer, as it accepts two parameters and performs an action without returning a value.
390
What is a common use case for BiConsumer in Java?
Operations requiring two parameters, such as Map.put(k, v) or formatting/printing two values.
391
In the following code, what is the lambda expression’s role?
It defines a BiConsumer that concatenates a String and Integer with a colon and prints the result.
392
Which interface would you choose for a zero-argument factory method that generates values?
Supplier, as it takes no inputs and returns a value (T).
393
Given the following Consumer chaining code, what will be printed to the console?
The output will be "1:Test,2:Test"
394
What is the purpose of the andThen() method in the Consumer interface when used as shown in this code?
The andThen() method creates a composed Consumer that performs the first operation (c1) followed by the second operation (c2) in sequence.
395
How does the Supplier interface enable lazy initialization in this code snippet?
The Supplier delays object creation until get() is called, preventing immediate instantiation of ExpensiveObject when it might not be needed.
396
What will be the output of this BiConsumer example with a Map?
The output will be: "Alice is 25 years old" "Bob is 30 years old"
397
In the Map.forEach example, what does the BiConsumer lambda expression represent?
The BiConsumer represents an operation that takes two parameters (name and age) and performs an action (printing them) for each entry in the Map.
398
What functional interface is being used in this code and what is its single abstract method?
The Supplier functional interface is being used, and its single abstract method is T get() which takes no arguments and returns a value.
399
What is the error in this Supplier usage, and how would you fix it?
The code fails to call get() on the Supplier. The correct version is: java String empty = s.get(); // Correct - invokes Supplier