View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

parseInt in Java: Syntax, Parameters, Return Value & Examples

Updated on 25/06/20259,602 Views

How do you convert a numeric string into an actual integer in Java?

The answer lies in the parseInt() method in Java, a utility from the Integer class that converts a string into a primitive int. It’s widely used in data processing, input validation, and reading numbers from user input or files.

This tutorial explains what Integer.parseInt() in Java does, how it works, and where it’s used. You’ll learn its method signature, accepted parameters, and what values it returns. We’ll also look at practical code examples and compare it with Integer.valueOf()—another method often confused with parseInt().

Want to sharpen your Java fundamentals for real-world projects? Explore upGrad’s Software Engineering Courses and learn Java, data structures, and object-oriented concepts from top instructors.

By the end, you’ll know exactly when and how to use parseInt() in real-world Java applications.

Parameters of parseInt() in Java

ParseInt in Java has the following parameters:

String s: This is the string you want to convert into an integer. It represents the numeric value that you want to extract from the string. The string can contain leading or trailing white spaces but must contain valid characters representing an integer. Non-numeric characters will cause a NumberFormatException to be thrown.

int radix (optional): This parameter specifies the radix or base of the number system for parsing. It is an option10al parameter typically used when dealing with numbers in non-decimal bases, such as binary, octal, or hexadecimal. The default radix is (decimal), but you can specify values ranging from 2 to 36.

Here is the ParseInt() in Java Syntax, which is made up of the above two parameters:

parseInt(string, radix);

Let us now explore the different ParseInt methods in Java.

Java Integer parseInt (String s) Method

The parseInt(String s) method in Java is a static method of the Integer class. It is used to parse the string representation of an integer and convert it into its corresponding primitive int value.

Syntax:

public static int parseInt(String s) throws NumberFormatException

In the above syntax, s is the string to be parsed as an integer. This parameter is compulsory. The method returns the parsed int value. If the string cannot be parsed as an integer, it throws a NumberFormatException.

Example:

string numberStr = "42";
int parsedInt = Integer.parseInt(numberStr);
System.out.println(parsedInt);

In this example above, the parseInt() method is called with the string "42". It successfully parses the string and converts it to the corresponding int value, which is then assigned to the variable parsedInt. The resulting value, 42, is then printed to the console.

Java Integer parseInt (String s, int radix) Method

The parseInt(String s, int radix) method in Java allows you to parse a string representation of an integer with a specified radix (base).

Syntax:

public static int parseInt(String s, int radix) throws NumberFormatException

In the above syntax, the radix is the base of the numeral system to be used for parsing. It can be an integer value between 2 and 36 (inclusive). This parameter is also compulsory. Similar to the previous method, this throws a NumberFormatException if the string cannot be parsed as an integer.

Example:

//First example
String binaryStr = "1010";
int parsedBinary = Integer.parseInt(binaryStr, 2);
System.out.println(parsedBinary); // Output: 10

//Second example
String hexStr = "FF";
int parsedHex = Integer.parseInt(hexStr, 16);
System.out.println(parsedHex); // Output: 255

In the first example, the parseInt() method is called with the binary string "1010" and a radix of 2. It successfully parses the binary string and converts it to the corresponding int value, which is 10. The result is then printed to the console.

In the second example, the parseInt() method is called with the hexadecimal string "FF" and a radix of 16. It parses the hexadecimal string and converts it to the corresponding int value, which is 255. Finally, the result is printed to the console.

Return Values of parseInt() in Java

Exceptions of parseInt() in Java

The parseInt() method in Java can throw a NumberFormatException if the string cannot be parsed as an integer.

Here are the common causes of this exception:

  • The string contains characters other than digits and an optional leading minus sign (-) or plus sign (+).
  • The string is empty or consists only of whitespace characters.
  • The string represents a value that is outside the range of the int data type.

Example:

try {
    String numberStr = "123abc";
    int parsedInt = Integer.parseInt(numberStr);
    System.out.println(parsedInt);
} catch (NumberFormatException e) {
    System.out.println("Failed to parse the string as an integer.");
}

In the example above, the string "123abc" cannot be parsed as an integer because it contains non-digit characters. Therefore, NumberFormatException is thrown. The exception is caught in a try-catch block, and a corresponding error message is printed.

It's important to handle the NumberFormatException appropriately in your code, as it indicates that the string could not be parsed as an integer.

Compatibility and Examples of parseInt in Java

The parseInt() method in Java is available in all versions of Java. It is a part of the Integer class, which is a fundamental class in the Java standard library. Thus, parseInt() is compatible with any version of Java that supports the Integer class, including Java 1.0 and later versions.

Here are some more examples of using the parseInt() method:

Example 1

public class upGradTutorials {
    public static void main(String[] args) {
        String numberStr = "42";
        int parsedInt = Integer.parseInt(numberStr);
        System.out.println(parsedInt); // Output: 42
    }
}

This example parses the string "42" as an integer and prints the parsed value, which is 42.

Example 2

public class upGradTutorials {
    public static void main(String[] args) {
        String binaryStr = "1010";
        int parsedBinary = Integer.parseInt(binaryStr, 2);
        System.out.println(parsedBinary); // Output: 10
    }
}

In this example, the binary string "1010" is parsed as an integer with a radix of 2, which represents binary. The parsed value, 10, is printed.

Example 3

public class upGradTutorials {
    public static void main(String[] args) {
        String invalidNumberStr = "abc";
        try {
            int parsedInt = Integer.parseInt(invalidNumberStr);
            System.out.println(parsedInt);
        } catch (NumberFormatException e) {
            System.out.println("Failed to parse the string as an integer.");
        }
    }
}

Here, the hexadecimal string "FF" is parsed as an integer with a radix of 16, which represents hexadecimal. The parsed value, 255, is printed.

Example 4

public class upGradTutorials {
    public static void main(String[] args) {
        String invalidNumberStr = "abc";
        try {
            int parsedInt = Integer.parseInt(invalidNumberStr);
            System.out.println(parsedInt);
        } catch (NumberFormatException e) {
            System.out.println("Failed to parse the string as an integer.");
        }
    }
}

This example tries to parse the string "abc" as an integer, but it throws a NumberFormatException since the string cannot be parsed as a valid integer.

Example 5

public class upGradTutorials {
    public static void main(String[] args) {
        String emptyStr = "";
        try {
            int parsedInt = Integer.parseInt(emptyStr);
            System.out.println(parsedInt);
        } catch (NumberFormatException e) {
            System.out.println("Failed to parse the string as an integer.");
        }
    }
}

In this example, an empty string is attempted to be parsed as an integer, which again throws a NumberFormatException since an empty string is not a valid integer representation.

Integer.valueOf() vs Integer.parseInt() with Examples

Table of difference

Integer.valueOf() returns an Integer object and allows null values as input, while Integer.parseInt() returns a primitive int value and only accepts valid integer strings.

Here's a table highlighting the differences between Integer.valueOf() and Integer.parseInt() in Java:

Parameters

Integer.valueOf()

Integer.parseInt()

Return Type

Integer object

int primitive

Input Type

String

String

Handling Null Values

Accepts null input and returns null

Does not accept null input

Parsing Non-Integers

Accepts non-integer values as input (e.g., "12.34")

Accepts only valid integer values as input (throws NumberFormatException for non-integer values)

Auto-Unboxing

Returns an Integer object that may require unboxing to int

Returns the primitive int directly

Usage

Useful when you need an Integer object for operations or to represent null values

Useful when you need the primitive int value for calculations or comparisons

Example of Integer.valueOf():

public class upGradTutorials {
    public static void main(String[] args) {
        String str = "123";
        Integer integerValue = Integer.valueOf(str); // Parsing string to Integer object
        int intValue = integerValue; // Unboxing Integer object to int
        System.out.println("Integer Value: " + integerValue); // Output: Integer Value: 123
        System.out.println("Primitive int Value: " + intValue); // Output: Primitive int Value: 123
    }
}

In the above example, we have a Java class named upGradTutorials with a main method. Inside the main method, we have a String variable called str, which is initialized with the value "123". This string represents the integer value that we want to parse.

To parse the string to an integer, we use the Integer.valueOf() method. We pass the str variable as an argument to Integer.valueOf(), which returns an Integer object representing the parsed integer value. We store this object in a variable called integerValue.

To obtain the primitive int value from the Integer object, we can simply assign the integerValue object to an int variable called intValue.

To display the parsed values, we use System.out.println() statements. We first print the value of the integerValue object, which represents the parsed integer value. In this case, it will output "Integer Value: 123". Then, we print the value of the intValue variable, which is the unboxed integer value. This will output "Primitive int Value: 123".

Example of Integer.parseInt():

public class upGradTutorials {
    public static void main(String[] args) {
        String str = "456";
        int parsedInt = Integer.parseInt(str); // Parsing string to primitive int
        System.out.println("Parsed int Value: " + parsedInt); // Output: Parsed int Value: 456
    }
}

In the upGradTutorials class, we have a main method, which serves as the entry point for the program. Inside the main method, we start by declaring and initializing a String variable named str with the value "456". This string represents the integer value that we want to parse.

To parse the string to an integer, we use the Integer.parseInt() method. We pass the str variable as an argument to Integer.parseInt(), which returns the primitive int value of the provided string. The parsed integer value is stored in the parsedInt variable of type int.

As usual, we display the parsed integer value, we use the System.out.println() statement. We concatenate the string "Parsed int Value: " with the parsedInt variable using the + operator, and this entire expression is passed as an argument to System.out.println(). The output will be "Parsed int Value: 456".

Conclusion

In conclusion, parseInt in Java is a powerful method that allows you to convert string representations of numbers into their corresponding integer values. It provides a convenient way to extract numeric data from strings, making it a fundamental tool in Java programming.

By mastering parseInt in Java, you can process user input, parse data from external sources, and perform calculations involving integers effectively. To learn more about such methods in Java you can consider signing up for a comprehensive online course offered by upGrad.

FAQs

1. What is parseInt in Java?

The parseInt() method in Java is used to convert a string containing numeric characters into a primitive int. It's part of the Integer class in the java.lang package and is commonly used for user input or string-to-number conversions.

2. How does Integer.parseInt() work in Java?

Integer.parseInt() in Java takes a string as input and returns its integer value. If the string is not a valid integer, it throws a NumberFormatException. It’s ideal for parsing numbers from user input or text files.

3. What are the parameters of parseInt() in Java?

The parseInt() method in Java accepts either one or two parameters:

A string containing digits

An optional radix (base), like 2 for binary or 16 for hexadecimal

Both forms convert the string to an int based on the specified base.

4. What is the return type of parseInt() in Java?

The parseInt() method returns an int value. It converts a numeric string into a 32-bit signed integer. If conversion fails, the method throws a NumberFormatException at runtime.

5. How is parseInt() different from valueOf() in Java?

parseInt() returns a primitive int, while valueOf() returns an Integer object. Use parseInt() when performance and memory are priorities, and valueOf() when you need object-oriented features like nullability or use in collections.

6. Can I use parseInt() with different number bases in Java?

Yes, Java’s parseInt() supports different radices. For example, Integer.parseInt("101", 2) returns 5. This makes it useful for converting binary, octal, or hexadecimal strings into integers.

7. What happens if the string passed to parseInt() is not a number?

If the input to Integer.parseInt() in Java is not a valid integer (e.g., "abc" or "12a"), the method throws a NumberFormatException. You should handle this using try-catch blocks in your code.

8. Is parseInt() case-sensitive for numeric strings?

No, parseInt() is not case-sensitive for numbers. However, when parsing hexadecimal or alphanumeric values (like "A" to "F" in base 16), the method accepts both uppercase and lowercase characters.

9. How to handle exceptions with parseInt() in Java?

Wrap the parseInt() call inside a try-catch block to catch NumberFormatException. This ensures your program doesn’t crash when invalid or unexpected input is passed for conversion.

10. Can I use parseInt() to parse floating-point numbers?

No, Integer.parseInt() only parses whole numbers. If you pass a decimal string like "12.5", it will throw a NumberFormatException. Use Double.parseDouble() or Float.parseFloat() for decimals.

11. Where is parseInt commonly used in Java projects?

parseInt() is commonly used in user input validation, reading numeric data from text files, converting form data into integers in web applications, or parsing command-line arguments that represent numbers.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Pavan Vadapalli

Author|900 articles published

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology s....

image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.