Signup/Sign In

Java Integer parseInt (String s) Method

Java parseInt(String s) method is the part of the Integer class of the java.lang package. This method is used to parse the string value as a signed decimal integer value.

It must be noted that the characters passed in the string must be all decimal except for the first character which is used to define the sign of the integer. It may be an ASCII minus '-' sign to depict a negative value or an ASCII plus '+' sign to depict a positive value.

Syntax:

public static int parseInt(String s) throws NumberFormatException

Parameters:

The parameter passed is the string value whose signed decimal Integer object is to be returned.

Returns:

Returns the signed decimal Integer object of the string value passed as a parameter.

Example 1:

Here, two strings are passed and are returned as their respective signed decimal Integer objects.

import java.lang.Integer;

public class StudyTonight 
{  
	public static void main(String[] args) 
	{  
		String s1 = "23"; 
		String s2 = "-23";
		int n1 = Integer.parseInt(s1);  //converts the passed string as signed positive integer
		int n2 = Integer.parseInt(s2);  //converts the passed string as signed negative integer

		System.out.println("Equivalent Integer object is : " + n1);
		System.out.println("Equivalent Integer object is : " + n2);
	}  
}  


Equivalent Integer object is : 23
Equivalent Integer object is : -23

Example 2:

Here is a user-defined example where anyone using this code can put a value of his choice and get the equivalent output.

import java.lang.Integer;
import java.util.Scanner;

public class StudyTonight 
{  
	public static void main(String[] args) 
	{  
		try
		{
			System.out.println("Enter Value");
			Scanner sc = new Scanner(System.in);
			String s = sc.nextLine();
			int n = Integer.parseInt(s);  //converts the passed string as signed integer
			System.out.println("Equivalent Integer object is : " + n);
		}
		catch(Exception e)
		{
			System.out.println("Invalid Input!!");
		}
	}  
}  


Enter Value
287
Equivalent Integer object is : 287
***************************************
Enter Value
-456
Equivalent Integer object is : -456
****************************************
Enter Value
0x567
Invalid Input!!

Live Example:

Here, you can test the live code example. You can execute the example for different values, even can edit and write your examples to test the Java code.



About the author:
A Computer Science and Engineering Graduate(2016-2020) from JSSATE Noida. JAVA is Love. Sincerely Followed Sachin Tendulkar as a child, M S Dhoni as a teenager, and Virat Kohli as an adult.