Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Purpose of parseInt Java method
3.
Working of parseInt() method 
4.
Types of parseInt Java methods
5.
Syntax of parseInt() in Java
6.
Parameters list of Java integer parseInt()
7.
Return values of the respective parseInt() variants
8.
Implementation of parseInt() methods
8.1.
Example 1:
8.2.
Example 2:
8.3.
Example 3:
9.
Handling Errors and Exceptions in parseInt Java method
10.
Comparisons with other conversion methods
11.
Ninja's toolkit for using the parseInt method in Java
12.
Advantages of the parseInt() in Java
13.
Frequently Asked Questions
13.1.
What is the purpose of parseInt() in Java?
13.2.
What does the parseInt() method return if the string cannot be converted to its int value?
13.3.
What is the return type of the parseInt() method in Java?
14.
Conclusion
Last Updated: Mar 27, 2024
Medium

parseInt() Method in Java

Author Riya Singh
1 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Hello Ninja, 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.

parseInt() Method in Java

You can also check out our article on Converting Java string to int, Duck Number in Java

Purpose of parseInt Java method

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 converts or 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.
Example:

class Example {  
    public static void main(String[] args) {  
    String str = "717";
    int num = Integer.parseInt(str);
    System.out.println(num + 3); 
    }  
}  

 

Output:

720

 

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

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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

types of parseInt java methods

There are three types of parseInt() Java methods.

1. 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.
 

2. 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.
 

3. 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.

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.

Implementation of parseInt() methods

The implementation of the parseInt() methods is explained better in the examples below. 

Example 1:

public class Example1 {  
    public static void main(String[] args) {  
        int decimalNum = Integer.parseInt("100");  
        int signedPositiveNum = Integer.parseInt("+20");  
        int signedNegativeNum = Integer.parseInt("-25");  
          
        System.out.println(decimalNum + signedPositiveNum * signedNegativeNum);  
    }  
} 

 

Output:

-400 

Example 2:

public class Example2 {  
    public static void main(String[] args) {  
        String str= "250";    
        int num=Integer.parseInt(str, 6);    
        System.out.println(str+100);   
        System.out.println("num = "+num);   
        System.out.println(num+100);    
    }  
}  

 

Output:

250100
num = 102
202

Example 3:

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);  
    }  
}  

 

Output:

x = 4
y = 640
z = -492

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.

 

Must Read Type Conversion in Java

Frequently Asked Questions

What is the purpose of parseInt() in Java?

The parseInt java method converts a string user input to its corresponding Integer value. The method to work with different number systems can also specify a radix.

What does the parseInt() method return if the string cannot be converted to its int value?

If a string cannot be converted to its integer value, an error of NumberFormatException is thrown. The compiler also throws exceptions like NullPointerException if the string is null or empty.

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

The parseInt() method parses the string representation of a string and returns integer data corresponding to the radix specified, which can range from 2 to 36. If the radix is not stated, a default value of 10 is assumed.

Conclusion

Congratulations on reaching the end of the blog. 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

 

If you liked our article, do upvote our article and help other ninjas grow. You can refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingSystem Design, and many more!

Head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences and interview bundles, follow guided paths for placement preparations, and much more!!


Happy Learning!!

Previous article
Java Scanner Nextdouble() method
Next article
What is an Object in OOPS(Object Oriented Programming)
Live masterclass