boolean

A boolean is a primitive data type in Java that can hold only two values:

  • true
  • false

Booleans are mainly used to:

  • Make decisions in programs (e.g. if something is true, do one thing; otherwise do something else)
  • Track states (e.g. is a user logged in? is a light switched on?)

Declaring a boolean

You create a boolean using the boolean keyword:

boolean isActive = true;
boolean isLoggedIn = false;

Primitive type

A boolean is a primitive type. It stores its value directly in memory, rather than storing a reference to an object. When you change a boolean’s value, the old value is simply replaced:

boolean isActive = true;
System.out.println(isActive); // true

isActive = false;
System.out.println(isActive); // false

Long wrapper class

Even though boolean is a primitive type, there is a corresponding wrapper class called Boolean (with a capital B). This class provides useful methods to work with boolean values. Below are some common methods

Conversion methods

Convert primitive boolean to Boolean object

boolean b = true;
Boolean obj = Boolean.valueOf(b);

Convert String to Boolean object

String s = "true";
Boolean obj = Boolean.valueOf(s); // case insensitive

Convert String to primitive boolean

String s = "true";
boolean b = Boolean.parseBoolean(s); // returns true or false. Case insensitive

Convert primitive boolean to String

boolean b = true;
String s = Boolean.toString(b);

Convert Boolean object to String

Boolean b = Boolean.TRUE;
String s = b.toString(); // returns "true"

Comparison methods

compare

Boolean.compare(true, false)

compareTo

Boolean b1 = true;
Boolean b2 = false;

b1.equals(b2); // false

Both compare and compareTo return these values:

  • 0 → if values are equal
  • -1 → if first is less than second
  • 1 → first is greater than second

equals

Boolean b1 = true;
Boolean b2 = false;

b1.equals(b2); // false
// returns true if both values are equal, else returns false

Summary

  • boolean stores true or false
  • boolean is used for decisions and states
  • boolean is a primitive type with no methods
  • Boolean is the wrapper class that gives the boolean primitive access to methods

Further Reading


Leave a Reply

Your email address will not be published. Required fields are marked *

This site builds beginner confidence through fundamental coding concepts and regular practice. Java is the primary language, but the techniques apply across all programming languages.

Learn. Practice. Master

Categories