Java Reference
In-Depth Information
Typically, you receive strings from external sources, for example, a file. If strings cannot be converted to numbers,
wrapper classes will throw a NumberFormatException . It is common to place the string parsing logic inside a
try-catch block and handle the exceptions.
The following snippet of code attempts to parse two strings into double values. The first string contains a valid
double and the second one an invalid double . A NumberFormatException is thrown when the parseDouble() method
is called to parse the second string.
String str1 = "123.89";
try {
double value1 = Double.parseDouble(str1);
System.out.println("value1 = " + value1);
}
catch (NumberFormatException e) {
System.out.println("Error in parsing " + str1);
}
String str2 = "78H.90"; // An invalid double
try {
double value2 = Double.parseDouble(str2);
System.out.println("value2 = " + value2);
}
catch (NumberFormatException e) {
System.out.println("Error in parsing " + str2);
}
value1 = 123.89
Error in parsing 78H.90
the java.math package contains BigDecimal and BigInteger classes. they are used to hold big decimal
and integer numbers, which do not fit into the primitive types double and long . these classes are mutable and they are
typically not called wrapper classes. Use them if you perform computations on big numbers and you do not want to lose
intermediate values that exceed the standard primitive type range.
Note
The Character Wrapper Class
An object of the Character class wraps a char value. The class contains several constants and methods that are useful
while working with characters. For example, it contains isLetter() and isDigit() methods to check if a character is
a letter and digit. The toUpperCase() and toLowerCase() methods convert a character to uppercase and lowercase.
It is worth exploring the API documentation for this class. The class provides a constructor and a factory valueOf()
method to create objects from a char . Use the factory method for better performance. The charValue() method
returns the char that the object wraps. The following snippet of code shows how to create Character objects and how
to use some of their methods:
// Using the constructor
Character c1 = new Character('A');
 
 
Search WWH ::




Custom Search