Learn how to convert String to Integer in Java 8 using Integer.parseInt() and Integer.valueOf() with a custom Functional Interfaces and method reference examples.
Code Explanation (Step-by-Step) :
- @FunctionalInterface is used to create a custom functional interface.
- The Converter interface accepts two generic types: F and T.
- F represents the input type, which is String in this example.
- T represents the output type, which is Integer in this example.
- Integer::parseInt is a method reference used to convert String to int.
- Integer::valueOf is a method reference used to convert String to Integer.
- The convert() method accepts a String value and returns the converted Integer value.
- Finally, the converted values are printed on the console.
@FunctionalInterface
interface Converter {
T convert(F from);
}
public class StringToInt {
public static void main(String[] args) {
Converter a = Integer::parseInt;
int d1 = a.convert("123");
System.out.println("Using Integer.parseInt() method: " + d1);
Converter b = Integer::valueOf;
Integer d2 = b.convert("456");
System.out.println("Using Integer.valueOf() method: " + d2);
}
}
Output :
Using Integer.parseInt() method: 123
Using Integer.valueOf() method: 456
Use Cases of String to Integer Conversion in Java
public class UserAgeExample {
public static void main(String[] args) {
String ageInput = "25";
int age = Integer.parseInt(ageInput);
if (age >= 18) {
System.out.println("User is eligible to vote.");
} else {
System.out.println("User is not eligible to vote.");
}
}
}
Output :
User is eligible to vote.
Difference Between parseInt() and valueOf()
| Method | Return Type | Example | Use Case |
|---|---|---|---|
Integer.parseInt() |
int |
Integer.parseInt("123") |
Use when you need primitive int |
Integer.valueOf() |
Integer |
Integer.valueOf("123") |
Use when you need Integer object |
FAQ
How do you convert String to Integer in Java 8?
You can convert String to Integer in Java 8 using Integer.parseInt() or Integer.valueOf(). Integer.parseInt() returns a primitive int, while Integer.valueOf() returns an Integer object.
What is the difference between parseInt() and valueOf() in Java?
Integer.parseInt() returns a primitive int value, whereas Integer.valueOf() returns an Integer wrapper object.
Can we use method reference to convert String to Integer in Java 8?
Yes, we can use method references like Integer::parseInt and Integer::valueOf with a functional interface to convert String to Integer in Java 8.