Java Program to demonstrate Boolean wrapper class
Program
import java.lang.Boolean;
public class javaLangBooleanDemo
{
public static void main(String[] args)
{
Boolean a = new Boolean(true);
System.out.println("Boolean value of 'a' is: " + a);
a = false;
System.out.println("Boolean value changed to: " + a);
}
}
This program demonstrates the use of the Boolean wrapper class, which provides an object representation for the primitive boolean data type.
1. Import Statement
import java.lang.Boolean;
- The
Booleanclass is part of thejava.langpackage, which is automatically imported in Java. - It provides methods and constants to work with
booleanvalues and represents them as objects.
2. Class Definition
public class javaLangBooleanDemo
- Defines the class
javaLangBooleanDemo.
3. Main Method
public static void main(String[] args)
- Entry point for the program.
4. Create a Boolean Object
Boolean a = new Boolean(true);
BooleanConstructor:- Creates a
Booleanobject that represents the primitive valuetrue. - The
Booleanwrapper class provides two constructors:Boolean(boolean value): Directly takes a boolean value.Boolean(String value): Accepts a string (case-insensitive). Returnstrueonly if the string equals"true". Example:Boolean b = new Boolean("true"); // true Boolean c = new Boolean("yes"); // false
- Creates a
- Note:
- The constructor
new Boolean(value)is deprecated in modern Java. UseBoolean.valueOf(true)orBoolean a = true(autoboxing).
- The constructor
5. Print the Initial Value
System.out.println("Boolean value of 'a' is: " + a);
- Prints the value of the
Booleanobjecta, which istrue. - The
toString()method is implicitly called to convert theBooleanobject to a string.
6. Modify the Boolean Value
a = false;
- This line assigns the primitive
booleanvaluefalseto the variablea. - Autoboxing: Automatically converts the primitive
boolean(false) to aBooleanobject.
7. Print the Modified Value
System.out.println("Boolean value changed to: " + a);
- Prints the updated value of
a, which isfalse.
Key Concepts
-
Wrapper Classes:
- The
Booleanwrapper class provides an object-oriented way to handlebooleanvalues.
- The
-
Autoboxing and Unboxing:
- Autoboxing: Converts a primitive
booleanto aBooleanobject automatically. Example:Boolean a = true; // Autoboxing - Unboxing: Converts a
Booleanobject to a primitivebooleanautomatically. Example:boolean primitive = a; // Unboxing
- Autoboxing: Converts a primitive
-
Deprecated Constructor:
- Using
new Boolean(value)is deprecated in favor ofBoolean.valueOf(value)in modern Java.
- Using
Output
Boolean value of 'a' is: true
Boolean value changed to: false