- Convert String to Int in Java
- Java – Convert String to Integer
- 1. Convert string to integer using Integer.parseInt()
- 2. String to Integer using Integer.valueOf()
- 3. Convert string to integer using Integer() constructor
- Conclusion
- Вопрос-ответ: как в Java правильно конвертировать String в int?
- Обсуждение
- Java String to Int – How to Convert a String to an Integer
- 1. Use Integer.parseInt() to Convert a String to an Integer
- 2. Use Integer.valueOf() to Convert a String to an Integer
- How to convert String to int in Java
- Conversion Modes
- parseInt(String) method
- What if String is not convertible to int
- Using valueOf(String) method
Convert String to Int in Java
In this Java tutorial, you will learn how to convert a given string value into an integer value using Integer.parseInt(), Integer.valueOf(), or Integer(), with examples.
Java – Convert String to Integer
You can convert a string value to int value in Java using Integer class. Most of the times, your application gets or reads data in the form of string. If you need to extract a number from that string and perform some numeric operations on it, it is necessary that you convert it to an integer or other numeric datatype.
You can typecast or convert a String to Integer in Java in many ways. Some of them are using Integer.parseInt(), Integer.valueOf(), new Integer().
1. Convert string to integer using Integer.parseInt()
Integer.parseInt(str) parses any parsable integer value from string to int value.
In this example, we shall use Integer.parseInt() method and pass a string that can be parsed to a valid int value.
Java Program
/** * Java Program - Convert String to Integer */ public class StringToInt < public static void main(String[] args) < //a string String str = "18966354"; //convert string to int int n = Integer.parseInt(str); System.out.print(n); >>
Run the above program and the String is converted to Integer.
If you do not provide a valid string that is parsable int, Integer.parseInt() throws NumberFormatException.
In the following example program, we shall take a string which does not contain a valid int value.
Some of the scenarios that could throw this error are:
- If the string contains invalid characters that does not parse to a int value. Like decimal point, alphabets, etc.
- A number that is out of range for a int value. Any value that is outside the range [-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807] will make parseInt() to throw this error.
Java Program
/** * Java Program - Convert String to Integer */ public class StringToInt < public static void main(String[] args) < //a string String str = "5.354"; //"as 9w0", "1as52" //convert string to int int n = Integer.parseInt(str); System.out.print(n); >>
Run the above program and parseInt() throws NumberFormatException.
Exception in thread "main" java.lang.NumberFormatException: For input string: "5.354" at java.base/java.lang.NumberFormatException.forInputString(Unknown Source) at java.base/java.lang.Integer.parseInt(Unknown Source) at java.base/java.lang.Integer.parseInt(Unknown Source) at StringToInt.main(StringToInt.java:12)
Also, if null is passed to Integer.parseInt(), the function throws NullPointerException.
Java Program
/** * Java Program - Convert String to Integer */ public class StringToInt < public static void main(String[] args) < //a string String str = null; //convert string to int int n = Integer.parseInt(str); System.out.print(n); >>
Run the above program and parseInt() throws NullPointerException.
Exception in thread "main" java.lang.NumberFormatException: null at java.base/java.lang.Integer.parseInt(Unknown Source) at java.base/java.lang.Integer.parseInt(Unknown Source) at StringToInt.main(StringToInt.java:12)
As Integer.parseInt() can throw NullPointerException or NumberFormatException, it is a good practice to surround the function parseInt() with Java Try Catch and handle the exceptions accordingly.
/** * Java Program - Convert String to Integer */ public class StringToInt < public static void main(String[] args) < //a string String str = "85612536"; int n = 0; try < //convert string to int n = Integer.parseInt(str); >catch (NumberFormatException e) < System.out.println("Check the string. Not a valid int value."); >catch (NullPointerException e) < System.out.println("Check the string. String is null."); >System.out.print(n); > >
2. String to Integer using Integer.valueOf()
You can also use Integer.valueOf() function to convert a string to int.
In the following example, we shall use the method valueOf() to get int value from string.
Java Program
/** * Java Program - Convert String to Integer */ public class StringToInt < public static void main(String[] args) < //a string String str = "85612536"; int n = 0; try < //convert string to int n = Integer.valueOf(str); >catch (NumberFormatException e) < System.out.println("Check the string. Not a valid int value."); >catch (NullPointerException e) < System.out.println("Check the string. String is null."); >System.out.print(n); > >
Just like Integer.parseInt(), the function Integer.valueOf() also throws NullPointerException if the string argument is null, or a NumberFormatException if the string does not parse to a valid int value.
3. Convert string to integer using Integer() constructor
Note: new Integer() constructor is depreciated. So, you may get warning when you are following this process. Integer.valueOf() is recommended in the place of new Integer().
You can also use the constructor of Integer class, to convert a string to int.
In the following example, we shall use the constructor of Integer class to convert from string to int.
Java Program
/** * Java Program - Convert String to Integer */ public class StringToInt < public static void main(String[] args) < try < Integer f = new Integer("52369"); System.out.print(f); >catch (NumberFormatException e) < System.out.println("Check the string. Not a valid int value."); >catch (NullPointerException e) < System.out.println("Check the string. String is null."); >> >
Conclusion
In this Java Tutorial, we learned how to Convert a String to Integer value in Java using Integer.parseInt() and Integer.valueOf() methods.
Вопрос-ответ: как в Java правильно конвертировать String в int?
int в String — очень просто, и вообще практически любой примитивный тип приводится к String без проблем.
int x = 5; String text = "X lang-java line-numbers">int i = Integer.parseInt (myString);
Если строка, обозначенная переменной myString , является допустимым целым числом, например «1», «200», Java спокойно преобразует её в примитивный тип данных int . Если по какой-либо причине это не удается, подобное действие может вызвать исключение NumberFormatException , поэтому чтобы программа работала корректно для любой строки, нам нужно немного больше кода. Программа, которая демонстрирует метод преобразования Java String в int , управление для возможного NumberFormatException :
public class JavaStringToIntExample < public static void main (String[] args) < // String s = "fred"; // используйте это, если вам нужно протестировать //исключение ниже String s = "100"; try < // именно здесь String преобразуется в int int i = Integer.parseInt(s.trim()); // выведем на экран значение после конвертации System.out.println("int i = " + i); >catch (NumberFormatException nfe) < System.out.println("NumberFormatException: " + nfe.getMessage()); >>
Обсуждение
Когда вы изучите пример выше, вы увидите, что метод Integer.parseInt (s.trim ()) используется для превращения строки s в целое число i , и происходит это в следующей строке кода:
int i = Integer.parseInt (s.trim ())
- Integer.toString (int i) используется для преобразования int в строки Java.
- Если вы хотите преобразовать объект String в объект Integer (а не примитивный класс int ), используйте метод valueOf () для класса Integer вместо метода parseInt () .
- Если вам нужно преобразовать строки в дополнительные примитивные поля Java, используйте такие методы, как Long.parseLong () и ему подобные.
Java String to Int – How to Convert a String to an Integer
Thanoshan MV
String objects are represented as a string of characters.
If you have worked in Java Swing, it has components such as JTextField and JTextArea which we use to get our input from the GUI. It takes our input as a string.
If we want to make a simple calculator using Swing, we need to figure out how to convert a string to an integer. This leads us to the question – how can we convert a string to an integer?
In Java, we can use Integer.valueOf() and Integer.parseInt() to convert a string to an integer.
1. Use Integer.parseInt() to Convert a String to an Integer
This method returns the string as a primitive type int. If the string does not contain a valid integer then it will throw a NumberFormatException.
So, every time we convert a string to an int, we need to take care of this exception by placing the code inside the try-catch block.
Let's consider an example of converting a string to an int using Integer.parseInt() :
String str = "25"; try < int number = Integer.parseInt(str); System.out.println(number); // output = 25 >catch (NumberFormatException ex)
Let's try to break this code by inputting an invalid integer:
String str = "25T"; try < int number = Integer.parseInt(str); System.out.println(number); >catch (NumberFormatException ex)
As you can see in the above code, we have tried to convert 25T to an integer. This is not a valid input. Therefore, it must throw a NumberFormatException.
Here's the output of the above code:
java.lang.NumberFormatException: For input string: "25T" 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 OOP.StringTest.main(StringTest.java:51)
Next, we will consider how to convert a string to an integer using the Integer.valueOf() method.
2. Use Integer.valueOf() to Convert a String to an Integer
This method returns the string as an integer object. If you look at the Java documentation, Integer.valueOf() returns an integer object which is equivalent to a new Integer(Integer.parseInt(s)) .
We will place our code inside the try-catch block when using this method. Let us consider an example using the Integer.valueOf() method:
String str = "25"; try < Integer number = Integer.valueOf(str); System.out.println(number); // output = 25 >catch (NumberFormatException ex)
Now, let's try to break the above code by inputting an invalid integer number:
String str = "25TA"; try < Integer number = Integer.valueOf(str); System.out.println(number); >catch (NumberFormatException ex)
Similar to the previous example, the above code will throw an exception.
Here's the output of the above code:
java.lang.NumberFormatException: For input string: "25TA" 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)
We can also create a method to check if the passed-in string is numeric or not before using the above mentioned methods.
I have created a simple method for checking whether the passed-in string is numeric or not.
public class StringTest < public static void main(String[] args) < String str = "25"; String str1 = "25.06"; System.out.println(isNumeric(str)); System.out.println(isNumeric(str1)); >private static boolean isNumeric(String str) < return str != null && str.matches("[0-9.]+"); >>
The isNumeric() method takes a string as an argument. First it checks if it is null or not. After that we use the matches() method to check if it contains digits 0 to 9 and a period character.
This is a simple way to check numeric values. You can write or search Google for more advanced regular expressions to capture numerics depending on your use case.
It is a best practice to check if the passed-in string is numeric or not before trying to convert it to integer.
You can connect with me on Medium.
Happy Coding!
How to convert String to int in Java
In this article, we are going to see how we can convert from a String data type into integer data type in Java.
Conversion Modes
There are two ways in which String data can be converted into integer. They are:
- Using the static method parseInt(String) of the java.lang.Integer wrapper class
- Using the static method valueOf(String) of the java.lang.Integer wrapper class
- Using the constructor of Integer wrapper class that takes String as its parameter
Let us see both the modes and how to do them.
parseInt(String) method
The class java.lang.Integer has a static method called parseInt(String) that allows the programmer to easily convert a String containing integer type data(i.e. numbers with no decimal points or post decimal values) into the corresponding Integer value. The function returns a value of primitive ‘int’ type.
Let us see a code snippet to illustrate the same:
The above code on execution provides the following output:
What if String is not convertible to int
If String is not convertible to int, you will get below exception.
Exception in thread “main” java.lang.NumberFormatException: For input string: “45.1”
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.valueOf(Integer.java:983)
at org.arpit.java2blog.java8.ConvertStringToInteger.main(ConvertStringToInteger.java:8)
Using valueOf(String) method
You can also use valueOf(String) method to convert String to int in java. You can call Integer’s intValue() to convert it to primitive type.