Wrapper Classes
- There is a wrapper class for every primitive in Java.
- They provide a mechanism to wrap primitives so that they can be handles like objects.
- They also provide an assortment of utility functions for primitives. Most of these functions are related to various conversions: converting primitives to and from String objects.
- Wrapper objects are immutable. Once they have been given a value, that value cannot be changed (however reference can be changed).
The Wrapper Constructors
- The following are the wrapper classes in the Java API:
- Those that take a String throw NumberFormatException if the String provided cannot be parsed into the appropriate primitive.
- If the String's case-insensitive value is "true" the Boolean will be true - any other value will equate to false.
- As of Java 5, a Boolean object can be used in a boolean test, because the compiler will automatically "unbox" the Boolean to a boolean.
Primitive | Wrapper Class | Constructor Arguments |
---|---|---|
boolean | Boolean | boolean or String |
byte | Byte | byte or String |
char | Character | char |
double | Double | double or String |
float | Float | float, double or String |
int | Integer | int or String |
long | Long | long or String |
short | Short | short or String |
All these constructors are now depricated (from version 9 and above).
xxxValue() Methods
When we need to convert the value of a wrapped numeric to primitive, use one of the many xxxValue() methods.
parseXxx() and valueOf() Methods
parseXxx() returns the named primitive of the type that invoked the method i.e., Integer.parseInt(String) will return an int value.
valueOf() returns a newly created wrapped object of the type that invoked the method i.e., Integer.valueOf(String) returns a new Integer object.
toString() Method
Class Object has a toString() method. All of the wrapper classes have a no-arg, non-static, instance version of toString(). This method returns a String with the value of the primitive wrapped in the object - for instance.
All of the wrapper classes provide an overloaded, static toString() method that takes a primitive numeric of the appropriate type and returns a String.
Finally, Integer and Long provide another static toString() method whose first argument is the primitive, and its second argument is radix.
toXxxString() Methods
The Integer and Long wrapper classes let us convert numbers in base 10 to binary, hexadecimal and octal. These conversion methods, takes an int or long, and return a String representation of the converted number.
Comments
Post a Comment