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);
}
}
Purpose
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
Boolean
class is part of thejava.lang
package, which is automatically imported in Java. - It provides methods and constants to work with
boolean
values 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);
Boolean
Constructor:- Creates a
Boolean
object that represents the primitive valuetrue
. - The
Boolean
wrapper class provides two constructors:Boolean(boolean value)
: Directly takes a boolean value.Boolean(String value)
: Accepts a string (case-insensitive). Returnstrue
only 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
Boolean
objecta
, which istrue
. - The
toString()
method is implicitly called to convert theBoolean
object to a string.
6. Modify the Boolean Value
a = false;
- This line assigns the primitive
boolean
valuefalse
to the variablea
. - Autoboxing: Automatically converts the primitive
boolean
(false
) to aBoolean
object.
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
Boolean
wrapper class provides an object-oriented way to handleboolean
values.
- The
-
Autoboxing and Unboxing:
- Autoboxing: Converts a primitive
boolean
to aBoolean
object automatically. Example:Boolean a = true; // Autoboxing
- Unboxing: Converts a
Boolean
object to a primitiveboolean
automatically. 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