Google+

248. Character Wrapper Class







Pre-requisites -



Character wrapper class is used to wrap the char primitive type into an object, whenever we need primitive type to be used as an object.

Example of wrapping char primitive type into an object using Character wrapper class -

char ch = 'a';
Character c1 = new Character(ch);  //Wrapping the char primitive type variable ch  into Character wrapper class type object c1


Example of unwrapping the Character wrapper class type object c1 into char primitive type variable c -

char c = c1.charValue( ) //Unwrapping the Character wrapper class type object c1 using charValue( ) method to char primitive data type variable c

Lets implement this on Eclipse IDE -

1. Launch Eclipse IDE, create a new Java Class 'CharacterWrapperClassDemo.java' with main( ) method in the existing Java Project 'Wrapper Classes' as shown below -



2. Declare a char primitive class type variable ch and assign it a value as shown below -


3. Now wrap the char primitive data type variable ch into a Character wrapper class type object c1 as shown below -


4. Now print the wrapped Character class type object 'c1' as shown below -


5. Save and Run the Java Class 'CharacterWrapperClassDemo.java' and observe that the char primitive data type value 'a' is printed using the wrapped object 'c1' in the output as shown below -


6. Now unwrap the Character class object c1 back to char primitive data type as shown below -


7. Print the unwrapped char primitive data type 'c' as shown below -


8. Save & Run the Java Class 'CharacterWrapperClassDemo.java' and observe that the char primitive data type value 'a' is printed using the unwrapped char primitive data type 'c' in the output as shown below -


Hence we can wrap the char primitive data type into an object using Character Wrapper Class and unwrap the object back to the char primitive data type using the charValue( ) method.







Please comment below to feedback or ask questions.

Boolean Wrapper Class will be explained in the next post.







No comments: