This tutorial explains the ways to convert Java String to Integer using Integer.parseInt and Integer.ValueOf methods with code examples:
We will cover the following two Integer class static methods that are used to convert Java String to int value:
- Integer.parseInt()
- Integer.valueOf()
=> Check ALL Java Tutorials Here
Table of Contents:
Java String To Int Conversion
Let’s consider a scenario, where we have to perform some kind of arithmetic operation on a number, but this number value is available in the form of a String. Let’s say the number is being retrieved as a text that is coming from the text field of a webpage or a text area of a web page.
In such a scenario, we have to first convert this String to retrieve numbers in an integer format.
For Example, let’s consider a scenario where we want to add 2 numbers. These values are retrieved as text from your webpage as “300” and “200” and we want to perform an arithmetic operation on these numbers.
Let’s understand this with the help of a sample code. Here, we are trying to add 2 numbers “300” and “200” and assign them to variable ‘c’. When we print ‘c’, we are expecting the output on a console as “500”.
package com.softwaretestinghelp; public class StringIntDemo{ public static void main(String[] args) { //Assign text "300" to String variable String a="300"; //Assign text "200" to String variable String b="200"; //Add variable value a and b and assign to c String c=a+b; //print variable c System.out.println("Variable c Value --->"+c);//Expected output as 500 } } Here is the program Output : Variable c Value --->300200
But, in the above program, the actual output printed on the console is
‘Variable c Value —>300200’.
What could be the reason for printing this output?
The answer to this is, when we did a+b, it is using the ‘+’ operator as concatenation. So, in c = a+b; Java is concatenating String a and b i.e. it is concatenating two strings “300” and “200” and printing “300200”.
So, this is happening when we try to add two strings:
So, what should be done if we want to add these two numbers?
For this, we first need to convert these strings to numbers and then perform an arithmetic operation on these numbers. In order to convert Java String to int, we can use the following methods provided by the Java Integer class.
- Integer.parseInt()
- Integer.valueOf()
Let’s see these methods one by one in detail.
#1) Using Java Integer.parseInt() Method
parseInt() method is provided by the class Integer class. The Integer class is called the Wrapper class as it wraps a value of the primitive type int in an object.
Let’s have a look at the method signature below :
public static int parseInt(String str) throws NumberFormatException
public static Integer valueOf(String str) throws NumberFormatException
This is a static method provided by the Integer class that returns an object of a class Integer having a value which is specified by the String object passed to it. Here, the interpretation of the argument passed is done as a signed decimal integer.
This is the same as the argument passed to the parseInt(java.lang.String) method. The result returned is an Integer class object which is representing the integer value specified by the String. In simple words, valueOf() method returns an Integer object equal to the value of
new Integer(Integer.parseInt(str))
Here, the ‘str’ parameter is a String containing the integer representation and the method returns an Integer object holding the value represented by the ‘str’ in the method.
This method throws an Exception NumberFormatException when the String does not contain a parsable integer.
Integer.parseInt() Method For String Without Signs
Let’s try to understand how to use this Integer.parseInt() method in the same Java program which we have seen in our earlier sample.
package com.softwaretestinghelp; /** * This class demonstrates sample code to convert String to int Java program * using Integer.parseInt() method using String having decimal digits without * ASCII sign i.e. plus + or minus - * */ public class StringIntDemo { public static void main(String[] args) { //Assign text "300" to String variable a String a="300"; //Pass a i.e.String “300” as a parameter to parseInt() //to convert String 'a' value to integer //and assign it to int variable x int x=Integer.parseInt(a); System.out.println("Variable x value --->"+x); //Assign text "200" to String variable b String b="200"; //Pass b i.e.String “200” as a parameter to parseInt() //to convert String 'b' value to integer //and assign it to int variable y int y=Integer.parseInt(b); System.out.println("Variable y value --->"+y); //Add integer values x and y i.e.z = 300+200 int z=x + y; //convert z to String just by using '+' operator and appending "" String c=z + ""; //Print String value of c System.out.println("Variable c value --->"+c); } }
Here is the program Output:
Variable x value —>300
Variable y value —>200
Variable c value —>500
So, now, we are able to get the desired output i.e. sum of the two numbers that are represented as text by converting those into int value and then performing an additional operation on these numbers.
Integer.parseInt() Method For String With Signs
As seen in the description of the above Integer.parseInt() method, the first character is allowed to be an ASCII minus sign ‘-‘ for the indication of a negative value or an ASCII plus sign ‘+’ for the indication of a positive value. Let’s try the same program with a negative value.
Let us see the sample program with values and signs like ‘+’ and ‘-‘.
We will use the signed String values like “+75” and “-75000” and parse those to integer and then compare to find a larger number between these 2 numbers:
package com.softwaretestinghelp; /** * This class demonstrates sample code to convert string to int Java * program using Integer.parseInt() method * on string having decimal digits with ASCII signs i.e. plus + or minus - * @author * */ public class StringIntDemo1 { public static void main(String[] args) { //Assign text "75" i.e.value with ‘+’ sign to string variable a String a="+75"; //Pass a i.e.String “+75” as a parameter to parseInt() //to convert string 'a' value to integer //and assign it to int variable x int x =Integer.parseInt(a); System.out.println("Variable x value --->"+x); //Assign text "-75000" i.e.value with ‘-’ sign to string variable b String b="-75000"; //Pass b i.e.String “-75000” as a parameter to parseInt() //to convert string 'b' value to integer //and assign it to int variable y int y = Integer.parseInt(b); System.out.println("Variable y value --->"+y); //Get higher value between int x and y using Math class method max() int maxValue = Math.max(x,y); //convert maxValue to string just by using '+' operator and appending "" String c = maxValue + ""; //Print string value of c System.out.println("Larger number is --->"+c); }
Here is the program Output:
Variable x value —>75
Variable y value —>-75000
Larger number is —>75
Integer.parseInt() Method For String With Leading Zeros
In some cases, we need to have arithmetic operations on the numbers with the leading zeros as well. Let’s see how to convert String having number with leading zeros to int value using the Integer.parseInt() method.
For Example, in some finance domain software systems, it is a standard format to have an account number or amount with leading zeros. Like, in the following sample program, we are calculating the maturity amount of the fixed deposit amount using the interest rate and fixed deposit amount.
Here, the amount is specified using leading zeros. These String values with leading zeros are parsed to integer values using Integer.
parseInt() method as seen in the below program:
package com.softwaretestinghelp; /** * This class demonstrates sample program to convert string with leading zeros to int java * using Integer.parseInt() method * * @author * */ public class StringIntDemo2{ public static void main(String[] args) { //Assign text "00010000" i.e.value with leading zeros to string variable savingsAmount String fixedDepositAmount="00010000"; //Pass 0010000 i.e.String “0010000” as a parameter to parseInt() //to convert string '0010000' value to integer //and assign it to int variable x int fixedDepositAmountValue = Integer.parseInt(fixedDepositAmount); System.out.println("You have Fixed Deposit amount --->"+ fixedDepositAmountValue+" INR"); //Assign text "6" to string variable interestRate String interestRate = "6"; //Pass interestRate i.e.String “6” as a parameter to parseInt() //to convert string 'interestRate' value to integer //and assign it to int variable interestRateVaue int interestRateValue = Integer.parseInt(interestRate); System.out.println("You have Fixed Deposit Interst Rate --->" + interestRateValue+"% INR"); //Calculate Interest Earned in 1 year tenure int interestEarned = fixedDepositAmountValue*interestRateValue*1)/100; //Calcualte Maturity Amount of Fixed Deposit after 1 year int maturityAmountValue = fixedDepositAmountValue + interestEarned; //convert maturityAmount to string using format()method. //Use %08 format specifier to have 8 digits in the number to ensure the leading zeroes String maturityAmount = String.format("%08d", maturityAmountValue); //Print string value of maturityAmount System.out.println("Your Fixed Deposit Amount on maturity is --->"+ maturityAmount+ " INR"); } }
Here is the program Output:
You have Fixed Deposit amount —>10000 INR
You have Fixed Deposit Interest Rate —>6% INR
Your Fixed Deposit Amount on maturity is —>00010600 INR
So, in the above sample program, we are passing ‘00010000’ to the parseInt() method and printing the value.
String fixedDepositAmount="00010000"; int fixedDepositAmountValue = Integer.parseInt(fixedDepositAmount); System.out.println("You have Fixed Deposit amount --->"+ fixedDepositAmountValue+" INR");
We will see the value displayed on the console as You have a Fixed Deposit amount —>10000 INR
Here, while converting into an integer value, the leading zeros are removed.
Then, we have calculated the fixed deposit maturity amount as ‘10600’ integer value and formatted the result value using %08 format specifier to retrieve leading zeros.
String maturityAmount = String.format("%08d", maturityAmountValue);
When we print the value of formatted String,
System.out.println("Your Fixed Deposit Amount on maturity is --->"+ maturityAmount+ " INR");
We can see the output getting printed on console as Your Fixed Deposit Amount on maturity is —>00010600 INR
NumberFormatException
In the description of Integer.parseInt() method , we have also seen an exception thrown by the parseInt() method i.e. NumberFormatException.
This method throws an Exception i.e. NumberFormatException when the String does not contain a parsable integer.
So, let’s see the scenario in which this exception is thrown.
Let’s see the following sample program to understand this scenario. This program prompts the user to enter the percentage scored and returns the Grade received. For this, it parses the String value entered by the user to an integer value.
Package com.softwaretestinghelp; import java.util.Scanner; /** * This class demonstrates sample code to convert string to int Java * program using Integer.parseInt() method having string with non decimal digit and method throwing NumberFormatException * @author * */ public class StringIntDemo3{ private static Scanner scanner; public static void main(String[] args){ //Prompt user to enter input using Scanner and here System.in is a standard input stream scanner = new Scanner(System.in); System.out.print("Please Enter the percentage you have scored:"); //Scan the next token of the user input as an int and assign it to variable precentage String percentage = scanner.next(); //Pass percentage String as a parameter to parseInt() //to convert string 'percentage' value to integer //and assign it to int variable precentageValue int percentageValue = Integer.parseInt(percentage); System.out.println("Percentage Value is --->" + percentageValue); //if-else loop to print the grade if (percentageValue>=75) { System.out.println("You have Passed with Distinction"); }else if(percentageValue>60) { System.out.println("You have Passed with Grade A"); }else if(percentageValue>50) { System.out.println("You have Passed with Grade B"); }else if(percentageValue>35) { System.out.println("You have Passed "); }else { System.out.println("Please try again "); } } }
Here is the program Output:
Let’s try with 2 different input values entered by the user.
1. With Valid integer value
Please Enter the percentage you have scored:82
Percentage Value is —>82
You have Passed with Distinction
2. With InValid integer value
Please Enter the percentage you have scored: 85a
Exception in thread “main” java.lang.NumberFormatException: For input string: “85a”
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at com.softwaretestinghelp.StringIntDemo3.main(StringIntDemo3.java:26)
So, as seen in the program output,
#1) When the user enters a valid value i.e. 82 as input, the output getting displayed on the console is as follows:
Percentage Value is —>82
You have Passed with Distinction
#2) When user enters invalid value i.e. 85a as input , output getting displayed on the console is as follows:
Please Enter the percentage you have scored:85a
Exception in thread “main” java.lang.NumberFormatException: For input string: “85a”
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at com.softwaretestinghelp.StringIntDemo3.main(StringIntDemo3.java:26)
java.lang.NumberFormatException is getting thrown while parsing 85a in Integer.parseInt() method as ‘85a’ has character ‘a’ which is not decimal digit nor ASCII sign ‘+’ or ‘-‘ i.e. ‘85a’ is not the parsable integer for Integer.parseInt() method.
So, this was about one of the ways of converting Java String to int. Let’s see the other way in which Java converts String to int i.e.using Integer.valueOf() method.
#2) Using Integer. valueOf () Method
valueOf() method is also Integer class static method .
Let’s have a look at the method signature below:
public static int parseInt(String str) throws NumberFormatException
This is a static method provided by the Integer class that returns an object of a classInteger having a value that is specified by the String object passed to it. Here, the interpretation of the argument passed is done as a signed decimal integer.
This is the same as the argument passed to the parseInt(java.lang.String) method. The result returned is an Integer class object is representing the integer value specified by the String. In simple words, the valueOf() method returns an Integer object equal to the value of new Integer(Integer.parseInt(str))
Here, the ‘str’ parameter is a String containing the integer representation and the method returns an Integer object holding the value represented by the ‘str’ in the method. This method throws the Exception NumberFormatException when the String does not contain a parsable integer.
Let’s understand how to use this Integer.valueOf() method.
Given below is a sample program. This sample code calculates the average temperature of 3 days of the week. Here, to convert temperature the values are assigned as a String value to an integer value. For this String to integer conversion, let’s try using the Integer.valueOf() method.
Package com.softwaretestinghelp; /** * This class demonstrates a sample program to convert string to integer in Java * using Integer.valueOf() method * on string having decimal digits with ASCII signs i.e.plus + or minus - * @author * */ public class StringIntDemo4 { public static void main(String[] args) { //Assign text "-2" i.e.value with ‘-’ sign to string variable sundayTemperature String sundayTemperature= "-2"; //Pass sundayTemperature i.e.String “-2” as a parameter to valueOf() //to convert string 'sundayTemperature' value to integer //and assign it to Integer variable sundayTemperatureValue Integer sundayTemperatureValue = Integer.valueOf(sundayTemperature); System.out.println("Sunday Temperature value --->"+ sundayTemperatureValue); //Assign text "4" to string variable mondayTemperature String mondayTemperature = "4"; //Pass mondayTemperature i.e.String “4” as a parameter to valueOf() //to convert string 'mondayTemperature ' value to integer //and assign it to Integer variable mondayTemperature Integer mondayTemperatureValue = Integer.valueOf(mondayTemperature); System.out.println("Monday Temperature value --->"+ mondayTemperatureValue); //Assign text "+6" i.e.value with ‘+’ sign to string variable //tuesdayTemperature String tuesdayTemperature = "+6"; //Pass tuesdayTemperature i.e.String “+6” as a parameter to valueOf() //to convert string 'tuesdayTemperature' value to integer //and assign it to Integer variable tuesdayTemperature Integer tuesdayTemperatureValue = Integer.valueOf(tuesdayTemperature); System.out.println("Tuesday Temperature value --->"+ tuesdayTemperatureValue); //Calculate Average value of 3 days temperature //avgTEmp = (-2+4+(+6))/3 = 8/3 = 2 Integer averageTemperatureValue = (sundayTemperatureValue+mondayTemperatureValue +tuesdayTemperatureValue)/3; //convert z to string just by using '+' operator and appending "" String averageTemperature = averageTemperatureValue+""; //Print string value of x System.out.println("Average Temperature over 3 days --->"+averageTemperature); } }
Here is the program Output:
Sunday Temperature value —>-2
Monday Temperature value —>4
Tuesday Temperature value —>6
Average Temperature over 3 days —>2
Exercise: If we can convert String values as seen above, we can try Strings having a decimal point
For Example, instead of “-2”, can we try “-2.5”?
Please try the above sample Code with parseInt() or valueOf() method assigning String sundayTemperature = “-2.5” ;
Hint: Read the method signature again about the parsable values.
Answer: If you try the above sample program with String sundayTemperature = “-2.5, it will throw NumberFormatException as values of the String argument for parseInt() and valueOf() are ASCII plus‘+’ or minus ’-‘ sign and decimal digits.
So, obviously ‘.’ is invalid. Also, as these two methods are provided by the Integer class, the floating-point values like “2.5” would be non-parsable values for these methods.
Thus, we have discusses both the methods of the Integer class for converting a String to int in Java.
FAQs About Converting String To Int In Java
Q #1) How can I convert String to int in Java?
Answer: In Java String to int conversion can be done using two ways i.e. using the following methods of Integer class methods:
- Integer.parseInt()
- Integer.valueOf()
Q #2) How do you parse an integer?
Answer: Integer class provides static methods that are used to parse integer value to convert String to int value i.e. parseInt() and valueOf().
Q #3) What is parseInt ()?
Answer: parseInt() is a static method provided by the Integer class which is used to convert Java String to int value where the String value is passed as an argument and the integer value gets returned by the method.
For Example, int x = Integer.parseInt(“100”) returns int value 100
Q #4) What is parsing in Java?
Answer: Parsing in Java is basically the conversion of the value of an object of one data type to another data type. For Example, Integer.valueOf(str) converts ‘str’ which is an object of String data type to an Integer data type object.
Conclusion
In this tutorial, we explored how to convert String to int in Java using the following wrapper class Integer static methods:
- Integer.parseInt()
- Integer.valueOf()
We also covered the case where NumberFormatException gets thrown for an invalid number String.
Further reading =>> 8 Methods to convert Integer to Sting in Java
=> Explore The Simple Java Training Series Here