Boolean Values

true and false

Very often a program needs a yes/no answer: Is the user logged in? Is the item in stock? Java has the boolean type for this, with only two values: true and false.

Example

public class Main {
    public static void main(String[] args) {
        boolean isJavaFun = true;
        boolean isFishTasty = false;
        System.out.println(isJavaFun);
        System.out.println(isFishTasty);
        System.out.println(!isJavaFun);
    }
}

Output

true
false
false

Naming Booleans

Tip: Name boolean variables as yes/no questions: isActive, hasStock, canEdit, shouldRetry. Then if (isActive) reads like English.

Example

You can also convert text to a boolean and back:

public class Main {
    public static void main(String[] args) {
        boolean flag = Boolean.parseBoolean("TRUE");   // case-insensitive
        boolean other = Boolean.parseBoolean("yes");   // anything else -> false
        System.out.println(flag + " " + other);
        System.out.println(String.valueOf(flag).length());
    }
}

Output

true false
4