Number Parsing Methods
Java Parsing Methods Overview
Java provides multiple methods for parsing numbers with different radixes:
graph LR
A[Parsing Methods] --> B[Integer.parseInt()]
A --> C[Integer.valueOf()]
A --> D[Long.parseLong()]
A --> E[Byte.parseByte()]
Key Parsing Methods
Method |
Return Type |
Radix Range |
Use Case |
Integer.parseInt() |
int |
2-36 |
Basic integer parsing |
Integer.valueOf() |
Integer object |
2-36 |
Object-based parsing |
Long.parseLong() |
long |
2-36 |
Large number parsing |
Byte.parseByte() |
byte |
2-36 |
Small number parsing |
Detailed Method Examples
1. Integer.parseInt() Method
public class ParsingDemo {
public static void main(String[] args) {
// Binary to Decimal
int binaryValue = Integer.parseInt("1010", 2); // Result: 10
// Hexadecimal to Decimal
int hexValue = Integer.parseInt("FF", 16); // Result: 255
// Custom radix parsing
int customRadix = Integer.parseInt("Z", 36); // Result: 35
System.out.println("Parsed values: " +
binaryValue + ", " + hexValue + ", " + customRadix);
}
}
2. Integer.valueOf() Method
public class ValueOfDemo {
public static void main(String[] args) {
// Object-based parsing
Integer decimalObj = Integer.valueOf("100"); // Decimal
Integer binaryObj = Integer.valueOf("1010", 2); // Binary
System.out.println("Parsed objects: " +
decimalObj + ", " + binaryObj);
}
}
Error Handling
public class ErrorHandlingDemo {
public static void main(String[] args) {
try {
// Incorrect radix or format will throw NumberFormatException
int invalidParse = Integer.parseInt("ABC", 10);
} catch (NumberFormatException e) {
System.out.println("Parsing error: " + e.getMessage());
}
}
}
Best Practices
- Always use try-catch for robust parsing
- Verify input before parsing
- Choose appropriate method based on number type
- Consider radix limitations (2-36)
Explore more advanced parsing techniques with LabEx's Java programming resources.