Open In App

String to int in Java

Last Updated : 22 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, while operating upon strings, there are times when we need to convert a number represented as a string into an integer type. We usually do this because we can operate with a wide flexible set of operations over strings. The method generally used to convert String to Integer in Java is parseInt() of the String class.

In this article, we will see how to convert a String to int in Java.

Java String to Int

Program to Convert Java String to int

Let us take an example straight away to get used to the working parseInt() method :

Java




// Java program to demonstrate working parseInt()
// Where No NumberFormatException is Thrown
 
// Main class
public class GFG {
    // Main driver method
    public static void main(String args[])
    {
        // Custom wide-varied inputs to illustrate
        // usage of valueOf() method
        int decimalExample = Integer.parseInt("20");
        int signedPositiveExample = Integer.parseInt("+20");
        int signedNegativeExample = Integer.parseInt("-20");
        int radixExample = Integer.parseInt("20", 16);
        int stringExample = Integer.parseInt("geeks", 29);
 
        // Print commands on console
        System.out.println(decimalExample);
        System.out.println(signedPositiveExample);
        System.out.println(signedNegativeExample);
        System.out.println(radixExample);
        System.out.println(stringExample);
    }
}


Output

20
20
-20
32
11670324



parseInt() Method in Java

There are two variants of this method:

  1. parseInt(String s): This function parses the string argument as a signed decimal integer.
  2. parseInt(String s, int radix): This function parses the string argument as a signed integer in the radix specified by the second argument.

Syntax of parseInt

public static int parseInt(String str); 
public static int parseInt(String str, int radix);

Parameters

  • str: String that needs to be converted to an integer.
  • radix: is used while the string is being parsed.

Return Type

  • Both methods convert the string into its integer equivalent. The only difference is that of the parameter radix. The first method can be considered with radix = 10 (Decimal).

Exception Thrown

Remember certain key points associated with both variants:

  1. The string can be null or of zero-length
  2. Value represented by the string is not a value of type int
  3. Specifically for the parseInt(String s, int radix) variant of the function: 
    • The second argument radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX
    • Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign ‘-‘ (‘\u002D’) or plus sign ‘+’ (‘\u002B’) provided that the string is longer than length 1
  4. If your String has leading zeroes, the parseInt() method will ignore them. 

Cases of parseInt() Method

Let’s take a random code snippet further understand the illustrations better.

Case 1: parseInt(“20”, 16)

returns 32 , (2)*16^1 + (0)*16^0 = 32

Case 2: parseInt(“2147483648”, 10)

throws a NumberFormatException

Case 3: parseInt(“99”, 8)

throws a NumberFormatException
Reason: 9 is not an accepted digit of octal number system

Case 4: parseInt(“geeks”, 28)

throws a NumberFormatException

Case 5: parseInt(“geeks”, 29)

returns 11670324, Reason: Number system with base 29 can have digits 0-9 followed by characters a,b,c… upto s

Case 6: parseInt(“geeksforgeeks”, 29)

throws a NumberFormatException as the Reason: result is not an integer.

Number Format Exceptions of parseInt() Method

Exceptions caused by parseInt() Method mentioned below:

Java




// Java Program to Demonstrate Working of parseInt() Method
// Where NumberFormatException is Thrown
 
// Main class
public class GFG {
    // Main driver method
    public static void main(String args[])
    {
        // NumberFormatException
        String invalidArguments = "";
       
          // invalidArguments Error empty string
         // passed
        int emptyString
            = Integer.parseInt(invalidArguments);
       
          // The Converted Intger is out of bound
          // Too large to be called Integer
        int outOfRangeOfInteger
            = Integer.parseInt("geeksforgeeks", 29);
       
          // Domain Number System
        int domainOfNumberSystem
            = Integer.parseInt("geeks", 28);
 
        // Print commands on console
        System.out.println(emptyString);
        System.out.println(outOfRangeOfInteger);
        System.out.println(domainOfNumberSystem);
    }
}


Output

Similarly, we can convert the string to any other primitive data type:

  1. parseLong(): parses the string to Long
  2. parseDouble(): parses the string to double If we want to convert the string to an integer without using parseInt(), we can use valueOf() method. It also has two variants similar to parseInt()
  3. Difference between parseInt() and valueOf(): parseInt() parses the string and returns the primitive integer type. However, valueOf() returns an Integer Object.

Note: valueOf() uses parseInt() internally to convert to integer. 

Another Approach for Converting a String to Integer

Apart from parseInt() Method in Java there is another method for conversion of String to Integer. Below is the implementation of valueOf() method that is

valueOf() Method

The Integer.valueOf() method converts a String into an Integer object. Let us understand this by an example.

Below is the implementation of the above method:

Java




// Java Program to Demonstrate
// Working of valueOf() Method
 
// Main class
public class GFG {
    // Main driver method
    public static void main(String args[])
    {
        // Custom wide-varied inputs to illustrate
        // usage of valueOf() method
        int decimalExample = Integer.valueOf("20");
        int signedPositiveExample = Integer.valueOf("+20");
        int signedNegativeExample = Integer.valueOf("-20");
        int radixExample = Integer.valueOf("20", 16);
        int stringExample = Integer.valueOf("geeks", 29);
 
        // Print statements
        System.out.println(decimalExample);
        System.out.println(signedPositiveExample);
        System.out.println(signedNegativeExample);
        System.out.println(radixExample);
        System.out.println(stringExample);
    }
}


Output

20
20
-20
32
11670324





Similar Reads

TimeZone getOffset(int, int, int, int, int, int) Method in Java with Examples
The getOffset(int era, int yr, int mon, int day, int dayOfWeek, int millisec) method of TimeZone class in Java is used to know the offset value of this TimeZone at a specific date or modified date in case of daylight savings, from the UTC or the Universal Time Coordinated. This offset value can be added to get the local time. Syntax: public abstrac
2 min read
ZoneOffset ofHoursMinutesSeconds(int, int, int) method in Java with Examples
The ofHoursMinutesSeconds(int, int, int) method of ZoneOffset Class in java.time package is used to obtain an instance of ZoneOffset using the offset in hours, minutes and seconds passed as the parameter. This method takes the hours, minutes and seconds as parameter in the form of int and converts it into the ZoneOffset. Syntax: public static ZoneO
2 min read
SimpleTimeZone setStartRule(int, int, int) method in Java with Examples
The setStartRule(int startofMonth, int startofDay, int startofTime) method of SimpleTimeZone class in Java is used to set a particular start rule of the day-light saving time to a fixed date within a given month. Syntax: public void setStartRule(int startofMonth, int startofDay, int startofTime) Parameters: The method takes three parameters: starto
2 min read
SimpleTimeZone setEndRule(int, int, int) method in Java with Examples
The setEndRule(int endofMonth, int endofDay, int endofTime) method of SimpleTimeZone class in Java is used to set a particular rule of the day-light saving time to a fixed date within a given month. Syntax: public void setEndRule(int endofMonth, int endofDay, int endofTime) Parameters: The method takes three parameters: endofMonth: This is of Integ
2 min read
HijrahDate of(int, int, int) method in Java with Example
The of() method of java.time.chrono.HijrahDate class is used to generate the date according to Islamic hijri calendar system by using the passed proleptic year, month and date. Syntax: public static HijrahDate of(int Year, int month, int dayOfMonth) Parameter: This method takes the following argument as a parameter: year: which is the integer value
2 min read
IsoChronology date(int, int, int) method in Java with Example
The date() method of java.time.chrono.IsoChronology class is used get the local date according to ISO calendar system for the given year, month and day. Syntax: public LocalDate date(int prolepticYear, int month, int dayOfMonth) Parameter: This method takes the following arguments as parameter. prolepticYear: integer proleptic year for the year fie
2 min read
JapaneseChronology date(int, int, int) method in Java with Example
The date() method of java.time.chrono.JapaneseChronology class is used get the local date according to japanese calendar system for the given year, month and day.Syntax: public JapaneseDate date(int prolepticYear, int month, int dayOfMonth) Parameter: This method takes the following arguments as parameter. prolepticYear: integer proleptic year for
2 min read
JapaneseDate of(int, int, int) method in Java with Example
The of() method of java.time.chrono.JapaneseDate class is used to generate the date according to japanese calendar system by using the passed proleptic year, month and date. Syntax: public static JapaneseDate of(int prolepticYear, int month, int dayOfMonth) Parameter: This method takes the following argument as a parameter: year: which is the integ
2 min read
JapaneseDate of(JapaneseEra,int, int, int) method in Java with Example
The of() method of java.time.chrono.JapaneseDate class is used to generate the date according to Japanese calendar system by using the passed proleptic year, month, date and JapaneseEra. Syntax: public static JapaneseDate of(JapaneseEra era, int yearOfEra, int month, int dayOfMonth) Parameter: This method takes the following argument as a parameter
2 min read
MinguoChronology date(int, int, int) method in Java with Example
The date() method of java.time.chrono.MinguoChronology class is used get the local date according to Minguo calendar system for the given year, month and day.Syntax: public MinguoDate date(int prolepticYear, int month, int dayOfMonth) Parameter: This method takes the following arguments as parameter. prolepticYear: integer proleptic year for the ye
2 min read