Converting Strings to Integers in Java

I was in the process of creating a simple calculator in java using Swing. My input fields include JTextFieald and JTextArea. These input fields are String, but I needed to deal with Integers in a calculator due to the mathematical calculations. This led me to thoughts of how I would be able to convert these Strings into integers?  That’s when I came across these two beneficial methods. The Integer.parseInt() and Interger.valueOf().

In this tutorial, we will discuss these two methods, but just before we jump, let’s have a quick overview of what are Strings in Java.

A string is a sequence of characters. In java, Strings are considered to be objects that represent the sequence of character values.  For example, if you have a word like “Student,” In this case, the student will be a String of 7 Characters. Once a string is created in java, it cannot be changed. Hence it’s an immutable object.

Creating a String

There are two ways of creating a string in java. One is by use of String literal, and the second is by using the new keyword.

String Literals

String website1 = "Codeunderscored";
String website2 = "Codeunderscored";

From the above example, the String is the series of characters enclosed in the double-quotes.

New Keyword

String website1 = new String ("Codeunderscored");
String website1 = new String ("Codeunderscored");

From the above two ways, you will note if we try to create two string instances such as ‘String website1 and String website2 using literals, and assing the two Strings the same values, the compiler will only create one String object having the value “Codeundescored”.  

This is where the second method comes in, using the new keyword. Suppose we incorporate the new keyword and still assign the strings the same values. Then, the compiler would create two different objects having the same String values.

Public class SringClass  {
    public static void main(String[] args)
    {
        // Declare String without using new operator
        String website = "Codeunderscored";
 
        // Prints the String.
        System.out.println("String Website = " + website);
 
        // Declare String using new operator
        String website1 = new String("Codeunderscored");
 
        // Prints the String.
        System.out.println("String Website = " +website1 );
    }
}

Output:

run:
String Website = Codeunderscored
String Website = Codeunderscored
BUILD SUCCESSFUL (total time: 0 seconds)

Converting String to int

Use Integer.parseInt().

This method returns the String as a primitive type. To perform mathematical operations, you will need to use int data type. Let’s take a scenario where we receive data from a TextArea. This entered data is in String format. Let’s now convert this data into an int using the Integer.Parse() method

public class StringClass{
  
 public static void main(String args[])
 {  
  //Declaring String variable  
  String number="300";
  
   String math = "400";
   
  //Converting String into int using Integer.parseInt()  
  int n=Integer.parseInt(number);
  int m=Integer.parseInt(math);
   
   int sum = n+m;
   
  //Printing the sum of te converted String 
  System.out.println("Sum = " +sum);  
  }
}

From the above code, we have two String with the value “300” and “400”. The method parseInt() takes ‘number’ and ‘math’ as arguments and returns the integer value after parsing. We then add the integer value returned and print out the summation.

Output:

run:
Sum = 700
BUILD SUCCESSFUL (total time: 0 seconds)

NumberFormatException

The Integer.parseInt( ) throws a NumberFrormatException if you pass an invalid String or if the String is empty.

public class StringClass {

    public static void main(String[] args)
    {
        String number = "mnop";
      
        int n=Integer.parseInt(number);;
      
        System.out.println(n); 
    }
}

Output:

Exception in thread "main" java.lang.NumberFormatException: For input string: "mnop"
	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 stringclass.StringClass.main(StringClass.java:10)
C:\Users\Admin\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)

Integer.valueOf()

This method returns the string as an integer class rather than a primitive type. In whichever case, the output will be the same.

public class StringClass{
  
 public static void main(String args[])
 {  
  //Declaring String variable  
  String number="300";
  
   String math = "400";
   
  //Converting String into int using valueOf() 
  int n=Integer.valueOf(number);
  int m=Integer.valueOf(math);
   
   int sum = n+m;
   
  //Printing the sum of te converted String 
  System.out.println("Sum = " +sum);  
  }
}

Output:

run:
Sum = 700
BUILD SUCCESSFUL (total time: 0 seconds)

These are the two main methods of converting String to int. Although programming is not limited, we also have some other methods to perform this operation.

Using Integer.decode()

public class StringClass {

    public static void main(String[] args)
    {
        String number = "300";
      
        int n = Integer.decode(number);
      
        System.out.println(n); 
    }
}

Output:

run:
300
BUILD SUCCESSFUL (total time: 0 seconds)

Using constructor – new Integer(String)

public class StringClass {

    public static void main(String[] args)
    {
        String number = "300";
      
        int n = new Integer (number);
      
        System.out.println(n); 
    }
}

Output:

run:
300
BUILD SUCCESSFUL (total time: 0 seconds)

Conclusion

Int data type is used to perform numeric arithmetic operations; even if a String object contains numeric data, you will need to convert it into int to perform calculations. In this tutorial, we have covered how to convert String to int with ease.

Happy Learning.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *