The Wrapper Classes | Komputasi | Suatu Permulaan

J.E.D.I.

4.4 The Wrapper Classes

Obviously, the primitive data types such as int, char and long are not objects. Thus, variables of these data types cannot access methods of the Object class. Only actual objects, which are declared to be of reference data type, can access methods of the Object class. There are cases, however, when you need an object representation for the primitive type variables in order to use Java built-in methods. For example, you may want to add primitive type variables to a Collection object. This is where the wrapper classes comes in. Wrapper classes are simply object representations of simple non-object variables. Heres the list of the wrapper classes. Primitive Data Type Corresponding Wrapper Class boolean Boolean char Character byte Byte short Short int Integer long Long float Float double Double Table 10: Primitive data types and their corresponding wrapper class The names of the different wrapper classes are quite easy to remember since they are very similar to the primitive data types. Also, note that the wrapper classes are just capitalized and spelled out versions of the primitive data types. Heres an example of using the wrapper class for boolean. class BooleanWrapper { public static void mainString args[] { boolean booleanVar = 12; Boolean booleanObj = new BooleanTRue; primitive to object; can also use valueOf method Boolean booleanObj2 = new BooleanbooleanVar; System.out.printlnbooleanVar = + booleanVar; System.out.printlnbooleanObj = + booleanObj; System.out.printlnbooleanObj2 = + booleanObj2; System.out.printlncompare 2 wrapper objects: + booleanObj.equalsbooleanObj2; object to primitive booleanVar = booleanObj.booleanValue; System.out.printlnbooleanVar = + booleanVar; } } The sample code gives the following output: booleanVar = false booleanObj = true booleanObj2 = false compare 2 wrapper objects: false Introduction to Programming II Page 65 J.E.D.I. booleanVar = true

4.5 The Process and the Runtime Class