Google+

249. Boolean Wrapper Class








Pre-requisites -



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

Example of wrapping boolean primitive type into an object using Boolean wrapper class -

boolean var = true;
Boolean v1 = new Boolean(var);  //Wrapping the boolean primitive type variable var  into Boolean wrapper class type object v1


Example of unwrapping the Boolean wrapper class type object v1 into boolean primitive type variable v -

boolean v = v1.booleanValue( ) //Unwrapping the Boolean wrapper class type object v1 using booleanValue( ) method to boolean primitive data type variable v

Lets implement this on Eclipse IDE -

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


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


3. Now wrap the boolean primitive data type variable var into a Boolean wrapper class type object v1 as shown below -


4. Now print the wrapped Boolean class type object 'v1' as shown below -


5. Save and Run the Java Class 'BooleanWrapperClassDemo.java' and observe that the boolean primitive data type value true is printed using the wrapped object 'v1' in the output as shown below -


6. Now unwrap the Boolean class object v1 back to boolean primitive data type as shown below -


7. Print the unwrapped boolean primitive data type 'v' as shown below -


8. Save & Run the Java Class 'BooleanWrapperClassDemo.java' and observe that the boolean primitive data type value true is printed using the unwrapped boolean primitive data type 'v' in the output as shown below -



Hence we can wrap the boolean primitive data type into an object using Boolean Wrapper Class and unwrap the object back to the boolean primitive data type using the booleanValue( ) method.






Please comment below to feedback or ask questions.

Boxing and Unboxing will be explained in the next post.







No comments: