Java read ints from string

Convert String to int in Java

In this article, we will take a look at how to convert String to int in Java. Converting String to an int or Integer is a common task and we will take a look at the following options for this conversion.

  1. Java – Convert String to int using Integer.parseInt() method.
  2. Java – Convert String to int using Integer.valueOf() method.

1. Convert String to Int using Integer.parseInt()

The parseInt method provide the following 2 options to convert a String to int in Java.

  1. parseInt(String s) – String for converting to int.
  2. parseInt(String s , int radix) – String with base of the number system.
Читайте также:  Javascript find link in text

In the first option, we pass a string as input parameter “345” and parseInt() return the integer value after parsing the input String.Here is a high level signature:

String input ="345"; int output = Integer.parseInt(input);

parseInt() can throws a NumberFormatException if the String can’t be converted.

public class ParseStringToInt < public static void main(String[] args) < String input ="345"; String invalid = "javadevjournal"; /** * Convert String to * integer with default radix */ int output = Integer.parseInt(input); System.out.println(output); //345 //base 16 conversion using the radix int base16 = Integer.parseInt(input, 16); System.out.println(base16); //837 //base 8 conversion using radix int base8 = Integer.parseInt(input, 8); System.out.println(base8); //229 //number format exception int number1 = Integer.parseInt(invalid); System.out.println(number1); //Exception in thread "main" java.lang.NumberFormatException: For input string: "javadevjournal" >>

Integer.ParseInt() will return an int primitive value.If efficiency is your concern and you only need primitive value, then using Integer.ParseInt() is the best option.

There are few other important point when you are converting String to integer using Integer.parsseInt() method.

  • Ensure that all characters in the String are digits.
  • The first character of the String can be a “-” sign

Here is a modified version of above example with “-” in the input string value.

public class ParseStringToInt < public static void main(String[] args) < String input = "-345"; int number = 445; /** * Convert String to * integer with default radix */ int output = Integer.parseInt(input); System.out.println(output); // -345 /*Let's do some calculation to make sure number conversion is working as expected */ number = number + output; System.out.println(number); //100 >>

2. Convert String to Int using Integer.valueOf()

The Integer.valueOf() method internally use the Integer.parsseInt() method. Here is the method definition from the JDK.

public static Integer valueOf(String s) throws NumberFormatException

There are few distinction between the Integer.valueOf() and Integer.parseInt() method. Let’s take a look at them for better understanding.

  1. The valueOf(String) method returns an object of Integer class whereas the parseInt(String) method returns a primitive int value.
  2. We can choose the output as int or Integer class based on our requirement, however keep in mind that there will be Unboxing.
  3. You should use Integer.parseInt() method if you need int value and efficiency is your primary target.

The Integer.valueOf() method provides the following variations

  1. valueOf(String s) – Accepts String and parse it to Integer.
  2. valueOf(int i) – takes int and parse it to Integer.
  3. valueOf(String s, int radix) – String with base of the number system.

Here is a snapshot for the method

String input ="345"; Integer output = Integer.valueOf(input);

Let’s take a look at the complete example to convert String to int

public class ParseStringToInt < public static void main(String[] args) < String input = "345"; int number = 445; /** * Convert String to * integer */ Integer output = Integer.valueOf(input); System.out.println(output); // 345 /* pass int to convert it to the Integer class */ Integer output1 = Integer.valueOf(number); System.out.println(output1); // 445 /* Conversion with a specific base type */ Integer base16 = Integer.valueOf(input, 16); System.out.println(base16); //837 Integer base32 = Integer.valueOf(input, 32); System.out.println(base32); //3205 >>

The valueOf uses parseInt internally. If efficiency is your concern do not use this method to convert String to int or Integer.

3. NumberFormat Exception

Both Integer.parseInt() and Integer.valueOf() can throw NumberFormatException if the string cannot be parsed as an integer or int

public class NumberFormatExceptionExample < public static void main(String[] args) < String invalidNumber = "abc"; parseIntNFException(invalidNumber); >public static void parseIntNFException(String number) < Integer result = Integer.parseInt(number); System.out.println(result); >public static void valueOfNFException(String number) < Integer result = Integer.valueOf(number); System.out.println(result); >>
Exception in thread "main" java.lang.NumberFormatException: For input string: "abc" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.parseInt(Integer.java:615) at NumberFormatExceptionExample.parseIntNFException(NumberFormatExceptionExample.java:13) at NumberFormatExceptionExample.main(NumberFormatExceptionExample.java:8)

Note: PraseInt() return a primitive value while valueOf() will always return new Integer object, ideally, if you just want to convert String to an int, it’s always better to avoid creating new Object.

4. Convert String to int using Integer.valueOf()

The Integer.decode(String s) method can also be used to convert String to int in Java. This method takes String as input parameter and decode it to Integer. It accepts the following

public class ParseStringToInt < public static void main(String[] args) < String input1 = "100"; String input2 = "0x12"; String input3 = "012"; /** * Convert String to * integer using Integer.decode() */ Integer output1 = Integer.decode(input1); System.out.println(output1); // 100 Integer output2 = Integer.decode(input2); System.out.println(output2); // 18 Integer output3 = Integer.decode(input3); System.out.println(output3); // 10 >>

Summary

In this article, we discussed the different options to convert string to int in Java. We saw how to convert it using Integer.valueOf() , Integer.parseInt() and Integer.decode() method.Follow our Java articles to get more in depth knowledge.

1 thought on “Convert String to int in Java”

Hi article is nice,
In Java there are two methods to convert String to Int, they are.
Integer.parseInt()
Integer.valueOf()

Источник

Java String to int Conversion – 10 Examples

Java String to int conversion can be done using the Integer wrapper class. There are two static methods for this purpose – parseInt() and valueOf().

Java String to int Conversion Methods

The Integer class provides 5 overloaded methods for the string to int conversion.

  • parseInt(String s): parses the string as a signed decimal value. The string should have only decimal digits. The first character can be ASCII minus sign (-) or plus sign (+).
  • parseInt(String s, int radix): parses the given string as the signed integer in the radix.
  • parseInt(CharSequence s, int beginIndex, int endIndex, int radix): The method is useful in parsing a substring to an integer. If the index values are invalid, IndexOutOfBoundsException is thrown. If the CharSequence is null, NullPointerException is thrown.
  • valueOf(String s): This method returns an Integer object. The string is parsed as a signed decimal value. It calls parseInt (s, 10) internally.
  • valueOf(String s, int radix): internally calls the parseInt(s, radix) method and returns the Integer object.

Important Points for String to int Parsing

  • All the parseInt() and valueOf() methods throw NumberFormatException if the string is not parsable.
  • The radix value should be in the supported range i.e. from Character.MIN_RADIX (2) to Character.MAX_RADIX(36), otherwise NumberFormatException is thrown.
  • The parseInt() methods return int primitive data type.
  • The valueOf() methods return an Integer object.
  • The valueOf() methods internally calls parseInt() methods.
  • Since Java supports autoboxing, we can use int and Integer in our program interchangeably. So we can use either parseInt() or valueOf() method to convert a string to integer.
  • The parseInt() method to parse substring was added to String class in Java 9 release.
  • The string should not contain the prefix used to denote an integer in the different radix. For example, “FF” is valid but “0xFF” is not a valid string for the conversion.
  • The valueOf() methods are present because it’s present in every wrapper class and String to convert other data types to this object. Recommended Read: Java String valueOf() method.

Java String to integer Examples

Let’s look at some examples for parsing a string to an integer using the parseInt() and valueOf() methods.

1. parseInt(String s)

jshell> Integer.parseInt("123"); $69 ==> 123 jshell> Integer.parseInt("-123"); $70 ==> -123 jshell> Integer.parseInt("+123"); $71 ==> 123 jshell> Integer.parseInt("-0"); $72 ==> 0 jshell> Integer.parseInt("+0"); $73 ==> 0

2. parseInt(String s, int radix)

jshell> Integer.parseInt("FF", 16); $74 ==> 255 jshell> Integer.parseInt("1111", 2); $75 ==> 15

3. parseInt(CharSequence s, int beginIndex, int endIndex, int radix)

jshell> String line = "Welcome 2019"; line ==> "Welcome 2019" jshell> Integer.parseInt(line, 8, 12, 10) $77 ==> 2019 jshell> String lineMixed = "5 in binary is 101"; lineMixed ==> "5 in binary is 101" jshell> Integer.parseInt(lineMixed, 0, 1, 10) $79 ==> 5 jshell> Integer.parseInt(lineMixed, 15, 18, 2) $80 ==> 5

Java String To Int Example

4. valueOf(String s)

jshell> Integer io = Integer.valueOf(123); io ==> 123 jshell> int i = Integer.valueOf(123); i ==> 123

The valueOf() method returns Integer object. But, we can assign it to int also because Java supports autoboxing.

5. valueOf(String s, int radix)

jshell> Integer.valueOf("F12", 16) $84 ==> 3858 jshell> int i = Integer.valueOf("F12", 16) i ==> 3858 jshell> int i = Integer.valueOf("077", 8) i ==> 63

6. NumberFormatException Example

jshell> Integer.parseInt("abc"); | Exception java.lang.NumberFormatException: For input string: "abc" | at NumberFormatException.forInputString (NumberFormatException.java:68) | at Integer.parseInt (Integer.java:658) | at Integer.parseInt (Integer.java:776) | at (#87:1) jshell> Integer.parseInt("FF", 8); | Exception java.lang.NumberFormatException: For input string: "FF" under radix 8 | at NumberFormatException.forInputString (NumberFormatException.java:68) | at Integer.parseInt (Integer.java:658) | at (#88:1) jshell>

7. NullPointerException when parsing substring

jshell> Integer.parseInt(null, 1, 2, 10); | Exception java.lang.NullPointerException | at Objects.requireNonNull (Objects.java:221) | at Integer.parseInt (Integer.java:701) | at (#89:1) jshell>

8. IndexOutOfBoundsException when parsing substring

jshell> Integer.parseInt("Hello 2019", 1, 100, 10); | Exception java.lang.IndexOutOfBoundsException | at Integer.parseInt (Integer.java:704) | at (#90:1) jshell>

9. NumberFormatException when radix is out of range

jshell> Integer.parseInt("FF", 50); | Exception java.lang.NumberFormatException: radix 50 greater than Character.MAX_RADIX | at Integer.parseInt (Integer.java:629) | at (#91:1) jshell>

10. Java String to int Removing Leading Zeroes

If the string is prefixed with zeroes, they are removed when converted to int.

jshell> Integer.parseInt("00077"); $95 ==> 77 jshell> Integer.parseInt("00077", 16); $96 ==> 119 jshell> Integer.parseInt("00077", 12); $97 ==> 91 jshell> Integer.parseInt("00077", 8); $98 ==> 63

Conclusion

Java String to int conversion is very easy. We can use either parseInt() or valueOf() method. Java 9 added another utility method to parse substring to an integer.

References:

Источник

String to Int in Java – How to Convert a String to an Integer

Ihechikara Vincent Abba

Ihechikara Vincent Abba

String to Int in Java – How to Convert a String to an Integer

When working with a programming language, you may want to convert strings to integers. An example would be performing a mathematical operation using the value of a string variable.

In this article, you’ll learn how to convert a string to an integer in Java using two methods of the Integer class — parseInt() and valueOf() .

How to Convert a String to an Integer in Java Using Integer.parseInt

The parseInt() method takes the string to be converted to an integer as a parameter. That is:

Integer.parseInt(string_varaible)

Before looking at an example of its usage, let’s see what happens when you add a string value and an integer without any sort of conversion:

In the code above, we created an age variable with a string value of «10».

When added to an integer value of 20, we got 1020 instead of 30.

Here’s a quick fix using the parseInt() method:

In order to convert the age variable to an integer, we passed it as a parameter to the parseInt() method — Integer.parseInt(age) — and stored it in a variable called age_to_int .

When added to another integer, we got a proper addition: age_to_int + 20 .

How to Convert a String to an Integer in Java Using Integer.valueOf

The valueOf() methods works just like the parseInt() method. It takes the string to be converted to an integer as its parameter.

The explanation for the code above is the same as the last section:

  • We passed the string as a parameter to valueOf() : Integer.valueOf(age) . It was stored in a variable called age_to_int .
  • We then added 20 to the variable created: age_to_int + 20 . The resulting value was 30 instead of 1020.

Summary

In this article, we talked about converting strings to integers in Java.

We saw how to convert a string to an integer in Java using two methods of the Integer class — parseInt() and valueOf() .

Источник

Оцените статью