- How to convert String to int in Java
- 1. Convert String to int
- 2.How to handle NumberFormatException
- 3. Integer.MAX_VALUE = 2147483647
- 4. Integer.parseInt(String) vs Integer.valueOf(String)
- 5. Download Source Code
- 6. References
- 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
- Вопрос-ответ: как в Java правильно конвертировать String в int?
- Обсуждение
- String to Int in Java – How to Convert a String to an Integer
- How to Convert a String to an Integer in Java Using Integer.parseInt
- How to Convert a String to an Integer in Java Using Integer.valueOf
- Summary
- Java get integer from string
- Java String to Integer Example: Integer.valueOf()
- NumberFormatException Case
- References
- Feedback
- Help Others, Please Share
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
How to convert String to int in Java
In Java, we can use Integer.parseInt(String) to convert a String to an int ; For unparsable String, it throws NumberFormatException .
Integer.parseInt("1"); // ok Integer.parseInt("+1"); // ok, result = 1 Integer.parseInt("-1"); // ok, result = -1 Integer.parseInt("100"); // ok Integer.parseInt(" 1"); // NumberFormatException (contains space) Integer.parseInt("1 "); // NumberFormatException (contains space) Integer.parseInt("2147483648"); // NumberFormatException (Integer max 2,147,483,647) Integer.parseInt("1.1"); // NumberFormatException (. or any symbol is not allowed) Integer.parseInt("1-1"); // NumberFormatException (- or any symbol is not allowed) Integer.parseInt(""); // NumberFormatException, empty Integer.parseInt(" "); // NumberFormatException, (contains space) Integer.parseInt(null); // NumberFormatException, null
1. Convert String to int
Below example uses Integer.parseInt(String) to convert a String «1» to a primitive type int .
package com.mkyong.string; public class ConvertStringToInt < public static void main(String[] args) < String number = "1"; // String to int int result = Integer.parseInt(number); // 1 System.out.println(result); >>
2.How to handle NumberFormatException
2.1 For invalid number or unparsable String, the Integer.parseInt(String) throws NumberFormatException .
String number = "1A"; int result = Integer.parseInt(number); // throws NumberFormatException
Exception in thread "main" java.lang.NumberFormatException: For input string: "1A" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67) at java.base/java.lang.Integer.parseInt(Integer.java:668) at java.base/java.lang.Integer.parseInt(Integer.java:786) at com.mkyong.string.ConvertStringToInt.main(ConvertStringToInt.java:18)
2.2 The best practice is catch the NumberFormatException during the conversion.
package com.mkyong.string; public class ConvertStringToInt < public static void main(String[] args) < String number = "1A"; try < int result = Integer.parseInt(number); System.out.println(result); >catch (NumberFormatException e) < //do something for the exception. System.err.println("Invalid number format : " + number); >> >
Invalid number format : 1A
3. Integer.MAX_VALUE = 2147483647
Be careful, do not convert any numbers greater than 2,147,483,647, which is Integer.MAX_VALUE ; Otherwise, it will throw NumberFormatException .
package com.mkyong.string; public class ConvertStringToInt2 < public static void main(String[] args) < // 2147483647 System.out.println(Integer.MAX_VALUE); String number = "2147483648"; try < int result = Integer.parseInt(number); System.out.println(result); >catch (NumberFormatException e) < //do something for the exception. System.err.println("Invalid number format : " + number); >> >
2147483647 Invalid number format : 2147483648
4. Integer.parseInt(String) vs Integer.valueOf(String)
The Integer.parseInt(String) convert a String to primitive type int ; The Integer.valueOf(String) convert a String to a Integer object. For unparsable String, both methods throw NumberFormatException .
int result1 = Integer.parseInt("1"); Integer result2 = Integer.valueOf("1");
5. Download Source Code
6. References
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!
Вопрос-ответ: как в 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 () и ему подобные.
String to Int in Java – How to Convert a String to an Integer
Ihechikara Vincent Abba
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() .
Java get integer from string
Java String to Integer Example: Integer.valueOf()
The Integer.valueOf() method converts String into Integer object. Let's see the simple code to convert String to Integer in Java.
NumberFormatException Case
If you don't have numbers in string literal, calling Integer.parseInt() or Integer.valueOf() methods throw NumberFormatException.
Exception in thread "main" java.lang.NumberFormatException: For input string: "hello" 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.parseInt(Integer.java:770) at StringToIntegerExample3.main(StringToIntegerExample3.java:4)
References
For Videos Join Our Youtube Channel: Join Now
Feedback
Help Others, Please Share
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter