This section of my java tutorial, we will be showing an example source code on how to convert a String into an Integer Object. Converting a string to Integer requires only a call to a static method of Integer class parseInt(String input). This method accepts a string parameter which of course gives as an Integer output.

Instructions in String to Integer Conversion

  • Get the length and width of a rectangle from user input
  • Convert the input to Integer
  • Calculate the area of rectangle using the formula Area = Length * Width
  • Make sure to provide mechanism to catch any invalid user input.

API that has been used on this example

The java.util.Scanner can parse the tokens into primitive data types using java regular expressions. One of the constructor of the Scanner class can take InputStream which would be leveraging to get the user input from console.

  • nextLine() – This method returns a String which corresponds to the skipped line of the Scanner object.
  • close() – this is required to avoid memory leak

Apart from using Scanner, we need to use also one of the methods of Integer class.

Java String to Integer Conversion

This sample source code demonstrates a practical example on the usage of parseInt static method of Integer class. This method converts a String input to Integer format and we would be leveraging that to give a more concrete example on calculating an area of a rectangle. This program takes two input, the Length and Width. Afterwards we will convert this into Integer format and then we will be using it to calculate the area of a rectangle. Since we are dealing with number it is imperative to validate the user input. A try catch block was in place on this java tutorial source code to handle any error on the input.

package com.javatutorialhq.tutorial;

import java.util.Scanner;

/*
 * This sample code shows how to convert a String input to Integer type
 * Java tutorial with example source code
 */
public class StringToInteger {

	@SuppressWarnings("resource")
	public static void main(String[] args) {
		System.out.println("Enter the dimensions of a rectangle");
		System.out.print("L:");
		Scanner s = new Scanner(System.in);
		try{
			// convert the string read from the scanner into Integer type
			Integer length = Integer.parseInt(s.nextLine());
			System.out.print("W:");
			s = new Scanner(System.in);
			Integer width = Integer.parseInt(s.nextLine());
			// Printing the area of rectangle
			System.out.println("Area of rectangle:"+width*length);
		}
		catch(NumberFormatException ne){
			System.out.println("Invalid Input");
		}
		finally{
			s.close();
		}

	}

}

[/sourcecode]

Sample Output in running the String to Integer Converter

Enter the dimensions of a rectangle
L:12
W:13
Area of rectangle:156