How to Convert String to Int Java – Sometimes, you feel like you need to convert string to int in c or string to int in java. There are different ways to work on this conversion, but many of them include some idea behind the algorithm. There’s this simple way to convert an integer into string (and vice versa). You can use it when you’re doing some manipulations with strings and integer data types.
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.
Table of Contents
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){
ex.printStackTrace();
}
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){
ex.printStackTrace();
}
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){
ex.printStackTrace();
}
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){
ex.printStackTrace();
}
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 output is:
true
true
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.
Java String to int Example: Integer.parseInt()
Let’s see the simple code to convert a string to an int in java.https://imasdk.googleapis.com/js/core/bridge3.489.0_en.html#goog_2062025507
- int i=Integer.parseInt(“200”);
Let’s see the simple example of converting String to int in Java.
- //Java Program to demonstrate the conversion of String into int
- //using Integer.parseInt() method
- public class StringToIntExample1{
- public static void main(String args[]){
- //Declaring String variable
- String s=”200″;
- //Converting String into int using Integer.parseInt()
- int i=Integer.parseInt(s);
- //Printing value of i
- System.out.println(i);
- }}
Output:
200
Understanding String Concatenation Operator
- //Java Program to understand the working of string concatenation operator
- public class StringToIntExample{
- public static void main(String args[]){
- //Declaring String variable
- String s=”200″;
- //Converting String into int using Integer.parseInt()
- int i=Integer.parseInt(s);
- System.out.println(s+100);//200100, because “200”+100, here + is a string concatenation operator
- System.out.println(i+100);//300, because 200+100, here + is a binary plus operator
- }}
Output:
200100 300
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.
- //Java Program to demonstrate the conversion of String into Integer
- //using Integer.valueOf() method
- public class StringToIntegerExample2{
- public static void main(String args[]){
- //Declaring a string
- String s=”200″;
- //converting String into Integer using Integer.valueOf() method
- Integer i=Integer.valueOf(s);
- System.out.println(i);
- }}
Output:
300
NumberFormatException Case
If you don’t have numbers in string literal, calling Integer.parseInt() or Integer.valueOf() methods throw NumberFormatException.
- //Java Program to demonstrate the case of NumberFormatException
- public class StringToIntegerExample3{
- public static void main(String args[]){
- String s=”hello”;
- int i=Integer.parseInt(s);
- System.out.println(i);
- }}
Output:
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)
How to Convert Int to String in Python
Steps
- Open your Python project in your text editor. You can use any basic text editor on your computer, or a Python-integrated coding editor.
- If you’re just starting out with Python, make sure to check out this article for more information about basic Python functions and mechanics.
- Find your integer variable’s name. Find the first instance you created your integer variable in your code, and note down the variable’s name.
- For example, if you define an integer as i = 5, your integer’s variable name is i and it’s value is 5.
- Type s = str(var) on a new line. Start a new line in your code, and enter the str() function.
- This function allows an explicit type conversion. You can use it to convert an integer to a string object .
- This will create new string object named s. This will be the string conversion of your integer.
- On some versions, you can also use the var.__str__() function instead of str(var).
- Replace var in the function with the name of your integer variable. This will allow you to pull the integer value from the specified variable, and convert it to a string object.
- For example, if you’re converting the integer variable i = 5, your new line should look like s = str(i).
- Press ↵ Enter or ⏎ Return on your keyboard. This will import your integer’s value, and convert it to string in the new string object.
- Type print "The number is " + s in a new line. This will pull your new string object, and print it with the text here below.
- If your new string object is named differently, replace s here with the name of your own string object.
- For example, if you did myNewString = str(i), then your line here should look like print "The number is " + myNewString.
- Press ↵ Enter or ⏎ Return on your keyboard. This will process the line command, and print your new string along with the text below.
- For example, if your initial integer value was 10, this will print The number is 10.
Conclusion
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.