How to Convert String to Int

How to Convert String to Int – 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 documentationInteger.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

  1. int i=Integer.parseInt(“200”);  

Let’s see the simple example of converting String to int in Java.

  1. //Java Program to demonstrate the conversion of String into int  
  2. //using Integer.parseInt() method  
  3. public class StringToIntExample1{  
  4. public static void main(String args[]){  
  5. //Declaring String variable  
  6. String s=”200″;  
  7. //Converting String into int using Integer.parseInt()  
  8. int i=Integer.parseInt(s);  
  9. //Printing value of i  
  10. System.out.println(i);  
  11. }}  

Test it Now

Output:

200

Understanding String Concatenation Operator

  1. //Java Program to understand the working of string concatenation operator  
  2. public class StringToIntExample{  
  3. public static void main(String args[]){  
  4. //Declaring String variable  
  5. String s=”200″;  
  6. //Converting String into int using Integer.parseInt()  
  7. int i=Integer.parseInt(s);  
  8. System.out.println(s+100);//200100, because “200”+100, here + is a string concatenation operator  
  9. System.out.println(i+100);//300, because 200+100, here + is a binary plus operator  
  10. }}  

Test it Now

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.

  1. //Java Program to demonstrate the conversion of String into Integer  
  2. //using Integer.valueOf() method  
  3. public class StringToIntegerExample2{  
  4. public static void main(String args[]){  
  5. //Declaring a string  
  6. String s=”200″;  
  7. //converting String into Integer using Integer.valueOf() method  
  8. Integer i=Integer.valueOf(s);  
  9. System.out.println(i);  
  10. }}  

Test it Now

Output:

300

NumberFormatException Case

If you don’t have numbers in string literal, calling Integer.parseInt() or Integer.valueOf() methods throw NumberFormatException.

  1. //Java Program to demonstrate the case of NumberFormatException  
  2. public class StringToIntegerExample3{  
  3. public static void main(String args[]){  
  4. String s=”hello”;  
  5. int i=Integer.parseInt(s);  
  6. System.out.println(i);  
  7. }}  

Test it Now

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

  1. 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.
  2. 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.
  3. 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).
  4. 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).
  5. Press ↵ Enter or ⏎ Return on your keyboard. This will import your integer’s value, and convert it to string in the new string object.
  6. 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.
  7. 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.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x