Parsing Strings To Primitive Types
Learn Java string parsing to primitive types with Integer.parseInt(), Double.parseDouble(), Float.parseFloat() methods. Convert string to int, double, boolean safely using try-catch blocks to handle NumberFormatException. Master Java number conversion techniques.
Sometimes, we will have a string that represents a number, and you need to convert it into a primitive type like int
, double
, or float
to perform calculations or other operations. This process is called parsing.
In this section, we’ll learn how to convert strings to primitive types using methods like Integer.parseInt()
, Double.parseDouble()
, and how to handle errors that might occur during parsing.
Why Do We Parse Strings to Numbers?
Numbers are often used as strings when working with user input, file data, or web responses. If you need to perform mathematical operations, compare numbers, or use them in calculations, you need to convert these strings into primitive types like int
, double
, or float
.
Basic Parsing Methods
Java provides different methods for parsing strings into primitive types. Each primitive type (like int
, double
, float
, etc.) has a corresponding parse method.
Parsing an Integer: Integer.parseInt()
If you have a string representing a whole number (like "123"
), you can convert it into an int
using Integer.parseInt()
.
String numberStr = "123";
int number = Integer.parseInt(numberStr); // Converts "123" to 123
System.out.println(number + 10); // Outputs: 133
Here, the string "123"
is converted into the integer 123
, which can then be used in mathematical operations.
Parsing a Double: Double.parseDouble()
For decimal numbers (like "12.34"
), you can use Double.parseDouble()
to convert the string into a double
.
String priceStr = "12.34";
double price = Double.parseDouble(priceStr); // Converts "12.34" to 12.34
System.out.println(price + 1.5); // Outputs: 13.84
Here, "12.34"
is converted into the double
value 12.34
.
Parsing Other Primitive Types
Java provides similar methods for other primitive types:
Float.parseFloat()
: Converts a string to afloat
.Long.parseLong()
: Converts a string to along
(for larger whole numbers).Boolean.parseBoolean()
: Converts a string to aboolean
(true
orfalse
).
Example: Parsing a Boolean
String trueStr = "true";
boolean flag = Boolean.parseBoolean(trueStr); // Converts "true" to true
System.out.println(flag); // Outputs: true
Handling Exceptions During Parsing
When parsing a string, things can go wrong if the string doesn’t represent a valid number or boolean. For example, trying to parse the string "abc"
into an integer will result in an error. These types of errors are called exceptions.
What is an Exception?
An exception is an event that occurs during the execution of a program that disrupts its normal flow. In this case, if the string doesn’t contain a valid number, Java will throw a NumberFormatException
.
Example of an Exception:
String invalidNumber = "abc";
int number = Integer.parseInt(invalidNumber); // Throws a NumberFormatException
If you try to run this code, Java will stop and throw a NumberFormatException
because "abc"
cannot be converted into an integer.
Handling Exceptions with try-catch
To prevent your program from crashing when an invalid string is encountered, you can use a try-catch
block. This allows you to handle the error gracefully.
Example: Using try-catch
to Handle Parsing Errors:
String numberStr = "abc";
try {
int number = Integer.parseInt(numberStr);
System.out.println("The number is: " + number);
} catch (NumberFormatException e) {
System.out.println("Invalid number format: " + numberStr);
}
In this example:
- The
try
block contains the code that might throw an exception. - The
catch
block handles theNumberFormatException
if it occurs. Instead of crashing, it prints a message saying that the format is invalid.
This approach ensures that your program can keep running smoothly, even if an error occurs during parsing.
List of Parsing Methods
Integer.parseInt()
: Converts a string to an integer (int
).Double.parseDouble()
: Converts a string to a double (double
).Float.parseFloat()
: Converts a string to a float (float
).Long.parseLong()
: Converts a string to a long (long
).Boolean.parseBoolean()
: Converts a string to a boolean (true
orfalse
).
Handling Exceptions
Use a try-catch
block to handle NumberFormatException
when parsing strings that might not be valid numbers.
Example of Handling Multiple Inputs:
String[] numbers = {"123", "456", "abc", "789"};
for (String numberStr : numbers) {
try {
int number = Integer.parseInt(numberStr);
System.out.println("Parsed number: " + number);
} catch (NumberFormatException e) {
System.out.println("Invalid number: " + numberStr);
}
}
In this example, the program will continue parsing valid numbers but will catch and handle invalid ones like "abc"
.