![]() |
VOOZH | about |
The IntConsumer interface is a specialized functional interface available in the java.util.function package, introduced in Java 8. It represents an operation that accepts a single int value as input and performs an action without returning any result.
Square = 25
Explanation: In this example, an IntConsumer is created using a lambda expression that calculates and prints the square of a number. The accept() method passes the value 5 to the IntConsumer, resulting in the output Square = 25.
@FunctionalInterface
public interface IntConsumer
The accept() method is the primary abstract method of the IntConsumer interface. It accepts a single primitive int value and performs the specified operation on it without returning any result
Syntax:
void accept(int value)
30
Explanation: In this example, an IntConsumer object is created using a lambda expression that multiplies the input value by 10 and prints the result. When accept(3) is called, the operation is executed and 30 is displayed.
The andThen() method is a default method of the IntConsumer interface that combines two IntConsumer operations into a single operation. The current operation executes first, followed by the operation passed as an argument.
Syntax:
default IntConsumer andThen(IntConsumer after)
30 9
Explanation: In this example, the andThen() method combines two operations. First, the multiply consumer prints 30, and then the square consumer prints 9. Both operations are executed in sequence on the same input value.
Exception : java.lang.NullPointerException
Explanation: In this example, andThen() is called with null instead of a valid IntConsumer. Since andThen() requires a non-null argument, it throws a NullPointerException, which is caught and displayed.
Example: To demonstrate how an Exception in the after function is returned and handled.
Exception : java.lang.ArithmeticException: / by zero
Explanation: In this example, two IntConsumer operations are chained using andThen(). The second operation attempts to divide by (a - 3), which becomes zero when a is 3. This causes an ArithmeticException, which is caught and printed.