Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Are you stuck with the conversion of your string data into integer value? Do not worry, for Coding Ninjas has got your back. In this article, we will cover the parseInt Java method in detail, along with appropriate examples, so you can get a firm hold on the topic.
In our everyday coding practice, we come across certain equations defined as string data types, and to calculate them, we need to convert the numbers in the string to integer values. The parseInt() method in Java convertsor parses the string representation of numeric data into actual integer values. With this method, we can get the string attribute which is a non-primitive data type, returned as an int primitive data type..
Syntax of parseInt() in Java
The syntax of parseInt() in java are:-
public static int parseInt(String str)
public static int parseInt(String str, int radix)
public static int parseInt(CharSequence seq, int startIndex, int endIndex, int radix)
Parameters list of Java integer parseInt()
The parameter list of parseInt() is given in the table below.
Parameter
Data Type
Description
str
String
The string value is to be parsed into an integer value.
radix
int
The radix or the number system must be followed while parsing the string.
startIndex
int
The starting index of the section of CharSequence, which is to be parsed.
endIndex
int
The ending index of the section of CharSequence, which is to be parsed.
seq
CharSequence
The CharSequence is to be converted to its corresponding Integer value.
Return values of the respective parseInt() variants
If a radix is specified in the parseInt() method, an integer value with the corresponding base (can be either two as in binary, 8 as in octal, or 10 as in decimal, or 16 as in hexadecimal) is returned. Else integer value in its decimal number system is returned as the default.
Example
Java
Java
class Example { public static void main(String[] args) { String str = "717"; int num = Integer.parseInt(str); System.out.println(num + 3); } }
You can also try this code with Online Java Compiler
Thus extracting numerical data from user input or files becomes more effortless. The parseInt() in Java is a pre-defined method in Java that is a part of the Integer class, which belongs to Java.lang package
Working of parseInt() method
As discussed earlier, the parseInt() method converts a string value to an integer value. But how does it do so? Lets us discuss the working of the Java Integer parseInt() method.
1. The parseInt() method first takes a string as input.
2. In the second step, it checks the first character of the input string to determine the sign (positive or negative).
3. If the first character is identified as a sign, it is removed from the string.
4. The method then iterates through the remaining string and converts each character to its corresponding integer value.
5. If a character in the string turns out to be a letter or a symbol, an exception is thrown.
6. After converting the entire string, an integer value is returned.
Types of parseInt Java methods
There are three types of parseInt() Java methods.
parseInt( String str)
This method converts a string value to a signed decimal int object. The string's first character may be a "+" or a "-" sign. The characters in the string should not include any letters or other symbols.
parseInt(String str, int radix)
This method converts a string value to a signed decimal int object of a particular number system known as radix. The radix's value can be either 2 as binary, 8 as octal, 10 as decimal, or 16 as hexadecimal. The default radix value used in Java is 10 if nothing is specified. The string's first character may be a "+" or a "-" sign. The characters in the string should not include any letters or other symbols.
parseInt(CharSequence seq, int startText, int endText, int radix)
This method converts the character sequence passed as an argument into a signed integer of a specified number system. The method has two extra parameters, the start index and end index, which specify the section of the character sequence to be parsed.
Implementation of parseInt() methods
The implementation of the parseInt() methods is explained better in the examples below.
Example 1
Java
Java
public class Example1 { public static void main(String[] args) { int decimalNum = Integer.parseInt("100"); int signedPositiveNum = Integer.parseInt("+20"); int signedNegativeNum = Integer.parseInt("-25");
public class Example3 { public static void main(String[] args) { int x = Integer.parseInt("100", 2); int y = Integer.parseInt("+280", 16); int z = Integer.parseInt("-350", 12); System.out.println("x = "+x); System.out.println("y = "+y); System.out.println("z = "+z); } }
You can also try this code with Online Java Compiler
Handling Errors and Exceptions in parseInt Java method
The following exceptions are thrown if the conventions are not followed while using the parseInt java method.
1. If the string parameter contains a null value, a NullPointerException is thrown.
2. A NumberFormatException is encountered if:
The string parameter passed does not include a valid number except the first character, which can be a "+" or "-" symbol.
The radix specified is less than the Character.MIN_RADIX
The radix specified is greater than the Character.MAX_RADIX Note: Character.MIN_RADIX = 2 and Character.MAX_RADIX = 36
3. The IndexOutOfBoundsException is thrown when
startIndex is negative
startIndex is greater than endIndex
endIndex is greater than the length of CharSequence or the string
Comparisons with other conversion methods
Method
Description
parseInt()
This method is used to convert string data to an integer primitive value.
The parseInt java method is a static method of the Integer class.
parseInt() works only for integers.
It gives an error if an integer is passed as an input parameter.
valueOf()
The valueOf() method is also a string representation of a number into an actual integer object.
This java method is static for Integer, Double, Float, etc. wrapper classes.
The valueOf() method works for all kinds of numbers. If a character is provided as a parameter, the method returns its corresponding Unicode.
If an Integer is passed as input, an integer object is returned after the conversion.
Double.parseDouble()
This method is used to parse a string value to a double value.
It is a static method of the Double class.
The Double.parseDouble() method works for all kinds of numbers.
Ninja's toolkit for using the parseInt method in Java
Some of the best practices while using the parseInt java method are:
Passing the radix as the parameter to the method is always recommended. If it is not specified, the compiler assumes a default value of 10.
There is always a possibility for the program having the parseInt() to throw a NumberFormatException. Thus it is advised to handle the exceptions properly to prevent the program from crashing. You can also use the try-catch blocks to handle the exceptions.
Check for the null or empty strings to avoid null pointer exceptions.
Advantages of the parseInt() in Java
The advantages of using parseInt() in Java are:
String to integer conversions: The parseInt method makes the conversion of string value from user input to integer value easier.
Base conversion: The java method also allows the conversion of the number to a specific radix. Thus conversion to binary and hexadecimal becomes simpler.
Error Handling: An exception of NumberFormatException is encountered if the string is invalid or cannot be converted to an integer. Thus debugging and error handling is done smoothly.
Consistency: The parseInt java method follows the standard Java naming convention for methods and hence is easy to recognize and use in programs. Its consistency in different platforms and versions of Java makes it a reliable and safe method for conversions.
parseInt() in Java converts a string representation of a number into an integer.
When can the parseInt() method be used?
parseInt() is used when converting string inputs to integers is required, such as handling user input or parsing numeric data from files.
How to convert "123" to 123 in Java?
To convert "123" (string) to 123 (integer) in Java, use Integer.parseInt("123").
Why do we use parseInt()?
parseInt() is used to transform string representations of numbers into integers for arithmetic operations or data processing in Java programs.
Conclusion
We discussed the implementation of the parseInt Java method along with some examples. The article also highlighted the advantages of using the parseInt() method. We hope this blog has helped you understand the use of the parseInt Java method. Keep feeding curiosity. Explore more of our articles on other topics of Java, such as