top

Search

Java Tutorial

.

UpGrad

Java Tutorial

String to int in Java

Introduction

A String in Java is a collection of characters, whereas an int is a primitive data type representing an integer number. The conversion of String to int in Java is sometimes necessary to carry out mathematical operations or store numerical data. Fortunately, there are various methods for data type conversions like String to long in Java or String to double in Java. 

Let us delve deep into the basics of converting a String data type into an int data type.

Overview

'Integer.parseInt()' is one of the most popular techniques to convert a String to int in Java. This method accepts a String and outputs an int value. 

'NumberFormatException' will be issued if the String supplied as an argument cannot be transformed to an int.

Only Strings with valid integer values can be converted using this technique. A 'NumberFormatException' will also be thrown for strings containing non-numeric characters or numbers too big to fit within an int data type. Hence, a try-catch block must be used to handle this exception.

'Integer.valueOf()' is a different function that can convert a String to int in Java. Similar to "parseInt()," this function produces an "Integer" object that encapsulates the int value rather than an int. This function can only convert Strings with valid integer values should also be noted. 

'NumberFormatException' errors are produced by strings containing non-numeric characters or numbers too big to fit within an int data type.

A Scanner object may also convert a String to int in Java. This function enables the user to enter a String and use the nextInt() method to transform it into an int. It's vital to remember, though, that this approach can only be applied to user input and cannot be used to convert Strings that are already in memory.

In this article, we will understand the methods of String to int in Java.

Variants of parseInt() Method

To turn a String into an int value in Java, use the 'Integer.parseInt()' function. Multiple variations of this technique support various input and return types. The variations of the "parseInt()" method are shown below, along with examples for each:

'parseInt(String s, int radix)': This version of 'parseInt()' enables using a particular radix or base while parsing the String. The basis of the number system is represented by the radix, an integer value between 2 and 36. Examples of radixes are 2, 8, and 16, which stand for binary (base 2), octal (base 8), and hexadecimal (base 16), respectively.

Here's an illustration:

String binaryString = "1010";
int decimalValue = Integer.parseInt(binaryString, 2);
System.out.println(decimalValue); // Output: 10

In this example, the binary String "1010" is converted to its decimal counterpart using a radix of 2 by the parseInt() function. There are 10 results.

‘parseInt(String s)’ is the most used version of 'parseInt(),' which converts a String argument into a signed decimal integer.

This is an example:

String str = "123";
int num = Integer.parseInt(str);
System.out.println(num); // Output: 123

The above example changes the String "123" into the integer number 123 using the parseInt() function.

'parseInt(CharSequence s, int start, int end, int radix)': This version of "parseInt()" enables a CharSequence (such as a StringBuilder or StringBuffer) to be partially parsed as an integer. The start and end arguments define the spectrum of the subsequence to be processed.

Here's an illustration:

String binaryString = "1010";
int decimalValue = Integer.parseInt(binaryString, 2);
System.out.println(decimalValue); // Output: 10

In this example, a StringBuilder object's indexes 1 through 4 (exclusively) are parsed into an integer number with a radix of 10 using the 'parseInt()' function. There are 234 results.

Key points associated with both the variants

Several important things to keep in mind about the Java versions of the "parseInt()" function

1. 'parseInt(String s, int radix)'

This version of "parseInt()" enables the usage of a certain radix or base while parsing the String. The radix, which stands for the number system's base, should be between 2 and 36. The String has to have digits that are valid in the given radix. 'NumberFormatException' will be issued if the String is not an acceptable integer in the chosen radix.

2. 'parseInt(String s)'

An input that is a String is parsed into a signed decimal integer. The decimal (base 10) formatted digits in the String must be correct.  A 'NumberFormatException' will be thrown if the String is not a legitimate decimal-formatted integer.

3. 'parseInt(CharSequence s, int start, int end, int radix)'

This version of "parseInt()" enables a CharSequence (such as a StringBuilder or  StringBuffer) to be partially parsed as an integer. The start and end arguments define the range of the subsequence to be parsed. The provided radix's valid digits must be included in the CharSequence. A 'NumberFormatException' will be issued if the CharSequence is not a valid integer in the chosen radix.

When using any of the 'parseInt()' method's variations, it's crucial to effectively manage the 'NumberFormatException'. To do this, enclose the method call in a try-catch block as seen in the example below:

try {
    int num = Integer.parseInt("abc");
} catch (NumberFormatException e) {
    System.out.println("Invalid input: " + e.getMessage());
}

When the String "abc" is attempted to be parsed as an integer, a NumberFormatException is issued. This code will detect this exception and output an error message.

parseInt() Method

'parseInt()' is a Java method that may be used to translate a String value to an integer. The 'parseInt()' function can be used as shown below:

1. Call the 'parseInt()' function and provide the argument of the String you wish to convert.

String str = "123";
int num = Integer.parseInt(str);

This example uses the 'parseInt()' function to turn the String value "123" into an int value.

2. The 'parseInt()' function produces a value of type int that reflects the transformed String.

Example:

System.out.println(num); 

This example prints the outcome of 'num' to the console, which produces the result "123".

The 'parseInt()' function may produce a 'NumberFormatException' if the supplied String does not represent a valid integer value, it is vital to remember this. You may use a try-catch block similar to this one to handle this exception:

String str = "abc";
try {
    int num = Integer.parseInt(str);
    System.out.println(num);
} catch (NumberFormatException e) {
    System.out.println("Invalid input: " + e.getMessage());
}

The String "abc" is supplied to the parseInt() function in this example, which will throw a NumberFormatException. A fail message is printed when the catch block's code is performed.

That is how you change a String into an int value using Java's parseInt() function.

Java String to int Example: Integer.parseInt()

Another instance to convert String to int in Java 8 or Java, in general, is the "Integer.parseInt()" method which is shown here:

public class Example {
    public static void main(String[] args) {
        String str1 = "123";
        String str2 = "-456";
        String str3 = "7.89"; // Invalid input
        int num1 = Integer.parseInt(str1);
        int num2 = Integer.parseInt(str2);
        try {
            int num3 = Integer.parseInt(str3);
        } catch (NumberFormatException e) {
            System.out.println("Invalid input: " + e.getMessage());
        }
         System.out.println(num1); // Output: 123
        System.out.println(num2); // Output: -456
    }
}

Three 'String' variables—'str1', 'str2', and'str3'—are used in this example. While the third variable has an incorrect input value, the first two have legal integer values.

The first two strings are transformed into "int" values using the "Integer.parseInt()" function and saved in the variables "num1" and "num2." The console then displays these variables.

Using "Integer.parseInt()," we also try to transform the third string into an "int" value. A 'NumberFormatException' is raised because this text contains a decimal point and is not a legitimate integer value. This exception is caught, and an error message is shown to the console.

This is a different example of how to transform a "String" into an "int" value in Java using the "Integer.parseInt()" method.

Java String to Integer Example: Integer.valueOf()

In this example, our 'String' variable 'str' has the value "123" in it. This text is transformed into an "Integer" object using the "Integer.valueOf()" function, and the resulting object is kept in the variable "num." The value of 'num' is then printed to the console, which is 123.

Example:

public class Example {
    public static void main(String[] args) {
        String str = "123";
        Integer num = Integer.valueOf(str);
        System.out.println(num); // Output: 123
    }
}

The 'Integer.valueOf()' function returns an 'Integer' object, not an 'int' value, which is a crucial distinction to make. The 'intValue()' function of the 'Integer' object may be used to get the matching primitive 'int' value if you need to use the integer value in a computation or comparison.

Here's an example:

public class Example {
    public static void main(String[] args) {
        String str = "123";
        Integer num = Integer.valueOf(str);
        int value = num.intValue();
        System.out.println(value); // Output: 123
    }
}

By invoking the 'intValue()' function of the 'Integer' object 'num' in this example, we can acquire the primitive 'int' value. The value of 'value' is then printed to the console and is also 123.

That was an explanation of Java's "Integer.valueOf()" function and how to use it to change a "String" object into an "Integer" object.

NumberFormatException Case

When an algorithm, such as "Integer.parseInt()" or "Integer.valueOf()," is used to convert a "String" to a numeric type but the input string is not a valid integer, the exception type known as "NumberFormatException" is issued.

A prime example of a 'NumberFormatException' is given below:

public class Example {
    public static void main(String[] args) {
        String str = "hello";
        try {
            int num = Integer.parseInt(str);
            System.out.println(num);
        } catch (NumberFormatException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

In this example, the value "hello" is stored in the "String" variable "str." We try to use the "Integer.parseInt()" function to turn this text into an "int" value. A 'NumberFormatException' is raised since the value "hello" is not an acceptable integer.

The 'try-catch' block is used to catch this exception, and the exception object's 'getMessage()' method is used to output an error message to the console.

This output includes details about the input text that resulted in the issue and shows that a "NumberFormatException" was raised.

To prevent unusual program behavior or crashes, it's crucial to handle 'NumberFormatException' errors in your code correctly. As in the example, a "try-catch" block may be used to do this, or the input string can first be validated before an attempt is made to convert it to a numeric type.

Conclusion

Converting a string to an integer in Java is a common task in programming. The `parseInt()` method provided by the `Integer` class is a popular way to convert a string to an integer. This method takes a `String` as input and returns an `int.`

The `parseInt()` method has two variants - one takes a single argument, and another takes two. The two-argument version allows the caller to specify the radix or base of the number system when converting the string to an integer. Care should be taken to handle cases where the input string is not a valid integer, which can result in a `NumberFormatException.`

FAQs

1. Is it very difficult to convert char to int Java?

Converting char to int in Java is especially simple since you can directly use the ASCII (American Standard Code for Information Interchange) values of the characters and directly convert their respective numbers into int. 

2. How do you handle a "NumberFormatException" in Java when changing a string to an integer?

The 'NumberFormatException' may be caught and elegantly handled using a 'try-catch' block in your program.

3. What distinguishes Java's "valueOf()" and "parseInt()" methods?

The methods "valueOf()" and "parseInt()" can both be used to convert a "String" to an "int," but the latter method yields an "Integer" object while the former yields a basic "int."

Leave a Reply

Your email address will not be published. Required fields are marked *