Tutorial Playlist
parseInt in Java is a method that is part of the Integer class. It allows you to convert strings into integers easily. Whether dealing with user input, reading data from a file, or manipulating data within your application, understanding how to use parseInt efficiently is essential.
This tutorial will help you develop a solid understanding of what is parseInt in Java and how to utilize parseInt to convert strings to integers. You will be equipped with the knowledge to handle common pitfalls that may arise during the conversion process.
In this tutorial, we'll walk you through the basics of using parseInt in Java program. We'll cover the syntax, different scenarios where this program comes in handy, parseInt in Java examples, handling exceptions, and some best practices to remember.
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.
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.
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.
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:
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.
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:
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.
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.
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.
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.
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() 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".
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.
1. What is the purpose of using parseInt in a Java program?
The purpose of using parseInt in a Java program is to convert a string representation of a number into an integer value.
2. What is an example of a parseInt in Java exception?
An example of a parseInt exception in Java is the NumberFormatException, which is thrown when the input string cannot be parsed as a valid integer.
3. Is parseInt in Java a static method?
Yes, parseInt in Java is a static method, meaning it can be called directly on the Integer class without requiring an instance of the class.
PAVAN VADAPALLI
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...