Table of contents
1.
Introduction
2.
How to Convert String to Integer in Java?
2.1.
1. Using Integer.parseInt() Method in Java
2.2.
Cases of parseInt() Method
2.3.
Number Format Exceptions of parseInt() Method
2.4.
2. Using Integer.valueOf() Method
3.
Frequently Asked Questions
3.1.
Why do we need to convert string to int in java? 
3.2.
What is the difference between Integer.valueOf() and Integer.parseInt()?
3.3.
How to convert string to integer without using any direct method in Java?
3.4.
What will happen if the String cannot be converted to an int?
4.
Conclusion
Last Updated: Dec 1, 2024
Easy

Converting Java String to Int

Author Saksham Gupta
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Java, converting a string to an integer is a common task, especially when handling user inputs or processing data from external sources. However, this conversion can be tricky if the string is not properly formatted or if the input contains non-numeric characters. In this blog, we will explore different methods to convert a string to an integer in Java.

Converting Java String to Int

Also Read About, Multithreading in java, and Duck Number in Java.

How to Convert String to Integer in Java?

In Java, converting a String to an int is a common requirement when working with user input, data parsing, or file handling. For instance, when you receive numerical data as a String (e.g., from a text field in a form or a configuration file), you need to convert it to an int for mathematical operations or logical comparisons. This conversion is essential to ensure that your program can process numerical data correctly and efficiently.

In Java, two primary methods exist for converting a string to an integer. Here’s a detailed explanation of both methods with examples:

1. Using Integer.parseInt() Method in Java

The first function that we use to convert java string to int is Integer.parseInt(). The string is returned as an int primitive type when we use this. Let's see an example code that will convert java string to int.

Syntax of parseInt

int number = Integer.parseInt(String s);

Parameters

  • s: The String to be parsed into an integer.

Return Type

  • int: The method returns an integer representation of the String. If the string cannot be parsed as an integer, a NumberFormatException is thrown.

We can see that compiler is giving is error. You can try it on online java compiler.

Cases of parseInt() Method

The parseInt() method in Java is used to convert a String into an integer. This method is commonly used when parsing numbers from user input, configuration files, or other data sources that provide numeric values as strings. The method can handle both positive and negative numbers, and it also allows for specifying a radix (e.g., binary, octal, decimal, hexadecimal) when parsing the string.

Number Format Exceptions of parseInt() Method

A NumberFormatException occurs when the parseInt() method is unable to convert the provided String into an integer due to invalid format or characters.

Example:

public class ParseIntExample {
    public static void main(String[] args) {
        try {
            int number = Integer.parseInt("123abc");
        } catch (NumberFormatException e) {
            System.out.println("NumberFormatException: " + e.getMessage());
        }
    }
}
You can also try this code with Online Java Compiler
Run Code

Explanation:

In this example, the string "123abc" contains non-numeric characters (abc), causing the parseInt() method to throw a NumberFormatException. The exception indicates that the string cannot be parsed as an integer.

2. Using Integer.valueOf() Method

Another approach to converting a String to an integer in Java is by using the valueOf() method. This method also belongs to the Integer class and works similarly to parseInt(). However, it returns an Integer object instead of a primitive int.

Syntax:

Integer.valueOf(String s);

Example:

Integer number = Integer.valueOf("123");

Explanation:

The valueOf() method converts the string "123" into an Integer object. This approach is useful when you need to work with Integer objects instead of primitive int values. If the string cannot be converted, a NumberFormatException will also be thrown.

Let's see an example code that will convert java string to int.

string s="69";
Integer integer = integer.valueOf(str);
System.out.println(integer);


Note: Similar to Integer.parseInt() A NumberFormatException will be thrown if the string does not include a valid number.

As a result, we must handle this exception every time we convert java string to int by placing the code within the try-catch block. Let's see the example and see the error that we will receive when we try to convert java string to int, which contains invalid input.

string s = "69P";
try
{
    Integer integer = integer.valueOf(str);
    System.out.println(integer);
}

catch (NumberFormatException ex)
{
    ex.printStackTrace();
}

Output

java.lang.NumberFormatException: For input string: "69P"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.valueOf(Integer.java:766)
at OOP.StringTest.main(StringTest.java:42)


Also check out Addition of Two Numbers in Java here.

Frequently Asked Questions

Why do we need to convert string to int in java? 

The first question that will come to your mind is why we should convert java string to int. It is commonly used when doing mathematical operations on a string containing a number. The entered data is received as a string whenever we get data from TextField or TextArea. We must convert the java string to int if the provided data is in numerical format..

What is the difference between Integer.valueOf() and Integer.parseInt()?

Integer.valueOf() returns an Integer object, while Integer.parseInt() returns a primitive int. Additionally, Integer.valueOf() caches values between -128 and 127, improving performance, whereas parseInt() always returns a primitive int.

How to convert string to integer without using any direct method in Java?

You can convert a string to an integer manually by iterating through each character, calculating its numeric value using ASCII, and adjusting for place values, effectively performing the conversion algorithmically without built-in methods.

What will happen if the String cannot be converted to an int?

If the string cannot be converted to an int, both Integer.parseInt() and Integer.valueOf() will throw a NumberFormatException, indicating the string is not a valid integer representation.

Conclusion

Converting a String to an int in Java is a fundamental operation that is crucial for handling user input, data processing, and other tasks where numerical data is represented as text. The parseInt() method is a straightforward and widely used approach for this conversion, but it must be used carefully to avoid NumberFormatException errors when dealing with improperly formatted strings.

Also check out - String Interview Questions In Java and, Why is Java Platform Independent

Live masterclass