In Java, we often receive numeric values in the form of text called strings. But to do some calculations or store them as numbers, we have to change them to an integer. For example, if the user inputs “25”, it comes as a string, and we have to convert it into a number to use it. Java provides two easy ways to do this: parseInt() and valueOf(). Both can change a string into a number. One returns a primitive int, while the other returns an Integer object
In this guide, you will learn how and when to use different methods to convert a string to int in Java with examples, and also know how to fix errors if the string is not valid.
Table of Contents:
Why Do We Convert Strings to Integers?
We convert strings to integers because sometimes we need to do some calculations with the numbers that are hidden inside the text.
There are many reasons to convert a string to an integer. Some of them are as follows:
1. To Perform Math Operations: You cannot perform math calculations on strings.
For example,
String age = "25"; // This is string
You cannot perform calculations directly on this text-based variable related to age; hence, there is a need to first convert the string to an integer to perform maths on this.
2. User Input is usually a String: When users enter data using a form or keyboard, it is captured as a string, like age or marks. The data entered in the form cannot perform calculations, hence it has to be converted to an Integer.
For example,
Scanner sc = new Scanner(System.in);
String age = sc.nextLine();
In the above example, if the user enters the number 30, it will be stored as “30”.
To calculate or validate it, we must convert it:
int realAge = Integer.parseInt(age);
Master Java Today - Accelerate Your Future
Enroll Now and Transform Your Future
3. Data from Files or APIs Comes as Strings: When reading from files, databases, or APIs, numeric data is often stored as strings. You need to convert it if you want to do calculations, make decisions, or sort or filter by number.
4. Comparisons Work Better with Integers: Comparing strings lexicographically can yield unexpected results, such as returning a negative value when the string ‘100’ is compared to ’20’.
System.out.println("100".compareTo("20"));
will return -1 as an output
While comparing the int as,
System.out.println(100 > 20);
will return the boolean value true
5. Memory Efficiency and Performance: Numbers take up less memory and are faster to process than strings during operations.
How to Convert a String to an Integer in Java
When you receive a number in the form of a string, like “123”, you can convert it to an integer by using the following 2 methods.
Method 1: Use Integer.parseInt() to Convert a String to an Integer
Integer.parseInt() is a method in Java that converts a String into an int, and takes a string that contains digits and returns it as a number. If the string has non-numeric characters, it throws a NumberFormatException.
How to use Integer.parseInt()
To use an Integer.parseInt() method, you have to follow the following syntax.
int var = Integer.parseInt(str);
The var is the int variable, and str is the String variable that has to be converted to an int.
Example:
A NumberFormatException occurs when the string is passed to Integer.parseInt() is not a valid integer, which means the string contains some characters that can not be converted into a number.
NumberFormatException can occur due to the following reasons:
- If a string contains any letter or symbol.
- If the string has any whitespace.
- If the string is empty.
- If the string is null
- If the number is too large for an int.
A try-catch block is used to handle NumberFormatException in a Java program.
- The try block contains code that may throw an exception.
- The catch block handles the exception if it occurs.
Example:
Output:
Method 2: Use Integer.valueOf() to Convert a String to an Integer
Integer.valueOf() is a method in Java that is used to convert a String into an Integer. It works just like Integer.parseInt(), but instead of returning a primitive int, it returns an Integer object.
If the string has non-numeric characters, it throws a NumberFormatException.
How to use Integer.valueOf()
To use an Integer.valueOf() method, you have to follow the following syntax.
Integer var= Integer.valueOf( str);
The var is the Integer variable, and str is the String variable that has to be converted to an int.
Output:
In the above Java program, the string str is ” 123″, which has a space at its beginning, due to which the Integer.valueOf() method is unable to convert it into an Integer, and a NumberFormatException is thrown
Get 100% Hike!
Master Most in Demand Skills Now!
Cases of parseInt() and Integer.valueOf() Methods
1. Valid positive number: This successfully converts the string into an integer because it contains only valid numeric characters.
For example,
Integer.parseInt("100"); // 100
2. Valid Negative number: This method also works for negative numbers.
For example,
Integer.parseInt("-50"); // -50
3. String with whitespace (invalid): If the string contains whitespace, it is considered invalid and throws a NumberFormatException because Java does not automatically remove the spaces when parsing the integers.
For example,
Integer.parseInt(" 42 "); // NumberFormatException
4. Alphabets in a string: If the string contains any non-numeric characters, it throws a NumberFormatException.
For example,
Integer.parseInt("1a2"); // NumberFormatException
Note: Always validate or clean your string before converting it with Integer.parseInt() to avoid exceptions.
5. Decimal Numbers: If the String has a decimal value in it, then NumberFormatException is thrown.
For example,
Integer num = Integer.valueOf("99.9");
6. Empty String: If the string is empty the NumberFormatException will be thrown.
For example,
Integer num = Integer.valueOf(" ");
Difference Between parseInt() and valueOf()
Both parseInt() and valueOf() are used to convert a string to an int, but they have key differences in return type and use cases.
Key difference between parseInt() and valueOf():
Feature | parseInt() | valueOf() |
---|
Return Type | int (primitive) | Integer (object) |
Autoboxing | No | Yes |
Memory Usage | Lower (no object creation) | Higher (caching may help) |
Use Case | Calculations, performance-sensitive tasks | Collections, null handling |
Note: Autoboxing is the automatic conversion of primitive types into their corresponding wrapper class objects.
Primitive int vs Integer Class
Feature | int (Primitive) | Integer (Wrapper Class) |
---|
Type | Basic data type | A class in Java |
Stores | A number | An object that holds a number |
Memory | Uses less memory | Uses more memory |
Speed | Faster | Slower than int |
Can be null | No | Yes |
Default value | 0 | null |
Use in collections | Not allowed directly | Allowed |
Has methods | No | Yes, like intValue(), compareTo() |
Autoboxing | Not possible | Yes, done automatically by Java |
Unboxing | Not needed | Yes, Java converts it to an int when needed |
When to Use parseInt() vs valueOf()?
The Integer.parseInt() method in Java is used to store numbers as a primitive int. It is good for situations where you only need to perform the calculations or just store the number in a variable. It cannot be used in Java collections like ArrayList, and it cannot be assigned null.
The Integer.valueOf() method in Java is used when you need to store the number in an object form, such as when using collections like ArrayList<Integer>, or when dealing with APIs, databases, or frameworks that expect objects.
Unlock Your Future in Java
Start Your Java Journey for Free Today
Conclusion
So far in this article, we have learned how we can convert a string to an int in Java using the parseInt() and valueOf() methods. Use parseInt() when you just need a number for math, and use valueOf() when you need the number as an object, like for storing in an ArrayList. Both methods throw a NumberFormatException if the string is not a valid numeric representation
If you want to learn more about Java, you may refer to our Java Course to become an expert in it.
String to Integer Java – FAQs
Q1. Why do we need to convert a string to an int in Java?
We often need to convert a string to an int while working with user inputs, reading data from files, or APIs where numerical data is stored in text format.
Q2. What is the difference between Integer.valueOf() and Integer.parseInt()?
The major difference between Integer.valueOf() and Integer.parseInt() is that valueOf() returns an Integer object (wrapper class), while parseInt() returns a primitive int.
Q3. How to convert a string to an integer without using any direct method in Java?
To convert a string to an integer without using any direct method, iterate through each character, subtract ‘0’ to get the numeric value, and build the number using multiplication and addition.
Q4. What will happen if the String cannot be converted to an int?
If the string cannot be converted to an int, Java throws a NumberFormatException.
Q5. How to check if a string is a valid number before converting?
Use a regular expression:
if (str.matches("\d+")) {
int num = Integer.parseInt(str);
}