The first function that I will cover here is a static valueOf() method. It takes as an argument a string and converts it to the desired wrapper object. In most cases you can also provide a second parameter that is an int radix which indicates the base of the first parameter. The valueOf() method is provided in most of the wrapper classes (except Character). It throws a NumberFormatException (it is not checked so you don't have to declare it) if the string provided can't be converted. Here are some legal uses of it:
Integer i1 = Integer.valueOf("3");
Integer i2 = Integer.valueOf(123);
Float f = Float.valueOf("2.2");
The second method is xxxValue() where in the place of xxx we can put any primitive. This function converts the value of a wrapped object to a primitive. The following code shows a few examples of how we should use it:
Float f = Float.valueOf("5.5");
byte b = f.byteValue();
short s = f.shortValue();
double d = f.doubleValue();
The next function that is important to remember is parseXXX(). It is static and takes a string as an argument and parses it into an appropriate primitive. It also throws NumberFormatException in case when the string arument is not well formated. Let's have a look at the following demonstration code:
double d = Double.parseDouble("123.456");
int i = Integer.parseInt("345");
byte b = Byte.parseByte("127");
And that's it! Three useful and important methods that we should know for the exam!
No comments:
Post a Comment