Converting Strings to Integers in Java

There are times when it is necessary to accept input as a string, yet you may need to take a value from that string and convert it into an integer for calculations. This is a very common practice in Java programming. It is especially useful in string arrays, when certain containers are meant to hold numbers, and they are needed for calculations. We perform this variable conversion with the following line of code: int i = Integer.parseInt(s); Where i is the new integer being declared, and s is the string variable that already has a value. Below is a short example program demonstrating this:
  1. import java.util.Scanner;
  2.  
  3. public class strtoint
  4. {
  5.  
  6.         public static void main(String[] args)
  7.         {
  8.  
  9.                 Scanner input = new Scanner(System.in);
  10.  
  11.                 System.out.print("Enter your age: ");
  12.  
  13.                 String s = input.nextLine();
  14.  
  15.                 int i = Integer.parseInt(s);
  16.  
  17.                 i = i * 2;
  18.  
  19.                 System.out.println("Double your age is " + i); //example output
  20.  
  21.         }
  22. }
An integer may also be converted into a string. This is somewhat less common, but worth learning at the same time. An instance where this may be used is converting an integer value string so that it may be stored inside a string array. Here is the code for converting an integer value into a string. String s = String.valueOf(i); Where s is the string being declared, and i is the integer which you wish to convert. As you can see, it is quite simple to convert both ways. I challenge you to try it out to convert a string array value into an integer, preform a calculation on it, and then put it back into the array. If there are any questions, let me know in the comments below.

Add new comment