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 the java.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 value true.
    • The Boolean wrapper class provides two constructors:
      1. Boolean(boolean value): Directly takes a boolean value.
      2. Boolean(String value): Accepts a string (case-insensitive). Returns true only if the string equals "true". Example:
        Boolean b = new Boolean("true"); // true
        Boolean c = new Boolean("yes");  // false
        
  • Note:
    • The constructor new Boolean(value) is deprecated in modern Java. Use Boolean.valueOf(true) or Boolean a = true (autoboxing).

5. Print the Initial Value

System.out.println("Boolean value of 'a' is: " + a);
  • Prints the value of the Boolean object a, which is true.
  • The toString() method is implicitly called to convert the Boolean object to a string.

6. Modify the Boolean Value

a = false;
  • This line assigns the primitive boolean value false to the variable a.
  • Autoboxing: Automatically converts the primitive boolean (false) to a Boolean object.

7. Print the Modified Value

System.out.println("Boolean value changed to: " + a);
  • Prints the updated value of a, which is false.

Key Concepts

  1. Wrapper Classes:

    • The Boolean wrapper class provides an object-oriented way to handle boolean values.
  2. Autoboxing and Unboxing:

    • Autoboxing: Converts a primitive boolean to a Boolean object automatically. Example:
      Boolean a = true; // Autoboxing
      
    • Unboxing: Converts a Boolean object to a primitive boolean automatically. Example:
      boolean primitive = a; // Unboxing
      
  3. Deprecated Constructor:

    • Using new Boolean(value) is deprecated in favor of Boolean.valueOf(value) in modern Java.

Output

Boolean value of 'a' is: true
Boolean value changed to: false