Basic Data Types & Wrapper Classes
For efficiency, JAVA makes a distinction between objects and basic data types. Occasionally, you have to be able to treat a basic type as an object - a thing with methods and members associated with it. What JAVA does is to have one special class of objects associated with each basic data type. These are called wrapper classes (they "wrap up" the basic data types as objects), and are listed here:
| Basic Type | Wrapper Class |
| boolean | Boolean |
| char | Character |
| byte | Byte |
| short | Short |
| int | Integer |
| long | Long |
| float | Float |
| double | Double |
Use basic types whenever you can, because they are more efficient.
To create an instance of a wrapper object, call a constructor method with a value of the basic type as the argurment --
int iBasic = 42; // a simple int
Integer iWrapper = new Integer(iBasic);
/* defines an instance/object of the Integer wrapper class with the value 42
*/
Each wrapper class has an appropriately named method for extracting a basic value from the wrapper class --
int iNewValue = iWrapper.intValue() ;
/* the 42 is extracted from iWrapper object and store in the basic int variable iNewValue
*/
Wrapper classes are useful places to put common methods we'd like to see associated with the basic data types.
Most of these methods are class or static methods - they are associated with the class rather than an instance of that class. To call them, you specify the name of the class and then add the dot (.) as usual followed by the method name and arguments.
Examples from the Character wrapper class --
| toLowerCase( ) and toUpperCase( ) - changes the case of the argument char firstChar = 'A'; char secondChar = Character.toLowerCase(firstChar); | |
| isLetter(), isDigit(), isLowerCase(), isUpperCase(), isWhiteSpace() - returns a
boolean value if the argument fits the set of characters identified by the name of
the method char isDigit(response); // returns true if response fits in 0-9, else returns false char isWhiteSpace(response); //true if space, tab, newline, form feed or carriage return |
From the Integer wrapper class --
| parseInt() - takes a String argument and returns
the corresponding int String stringValue = "123" ; int intValue = Integer.parseInt(stringValue); | |
| toString() - converts and int argument to a String int intValue = 456 ; String newStringValue = Integer.toString(intValue);
Using the java.util package, the Random class might exist that would be used to generate random numbers -- static Random rand = new Random(); Then the following method would return a random integer in the (inclusive) range of 1 to the value of the argument supplied - public static int random(int n) |
![]()
Last updated by DrB on 18 February 2009