The IntSupplier interface is a specialized functional interface introduced in Java 8 and available in the java.util.function package. It represents a supplier of int values and does not accept any input arguments. It is commonly used when an integer value needs to be generated, calculated, or supplied on demand.
- Primitive specialization of Supplier<Integer>.
- Avoids boxing and unboxing overhead.
- Supports lambda expressions and method references.
import java.util.function.IntSupplier;
public class Main {
public static void main(String[] args) {
IntSupplier randomNumber =
() -> (int) (Math.random() * 100);
System.out.println(randomNumber.getAsInt());
}
}
Output
6
Explanation: In this example, the IntSupplier generates a random integer value between 0 and 99. The getAsInt() method retrieves and returns the generated value.
Syntax
@FunctionalInterface
public interface IntSupplier
Return Value: Returns an int value.
Example 1: Generate a Roll Number
import java.util.function.IntSupplier;
public class Main {
public static void main(String[] args) {
IntSupplier rollNumber = () -> 101;
System.out.println("Roll Number: "
+ rollNumber.getAsInt());
}
}
Output
Roll Number: 101
Explanation: The IntSupplier supplies a fixed roll number whenever getAsInt() is called.
Example 2: Return Current Year
import java.time.Year;
import java.util.function.IntSupplier;
public class Main {
public static void main(String[] args) {
IntSupplier currentYear =
() -> Year.now().getValue();
System.out.println(currentYear.getAsInt());
}
}
Output
2026
Explanation: The supplier retrieves and returns the current year using the Java Date-Time API.
Example: Java program to illustrate getAsInt method of IntSupplier Interface
import java.util.function.IntSupplier;
public class GFG {
public static void main(String args[])
{
// Create a IntSupplier instance
IntSupplier
sup
= () -> (int)(Math.random() * 10);
// Get the int value
// Using getAsInt() method
System.out.println(sup.getAsInt());
}
}
Output
7
Explanation: In this example, an IntSupplier is created using a lambda expression that generates a random integer between 0 and 9. The getAsInt() method retrieves and returns the generated value, which is then printed on the screen. The output may vary each time the program runs.
Advantages of IntSupplier
- Avoids boxing and unboxing of Integer objects.
- Improves performance when working with primitive int values.
- Supports lambda expressions and method references.
- Useful for generating counters, random values, and calculations.
- Simplifies functional-style programming.
- Ideal for lazy evaluation and value generation.