Skip to main content
Engineering LibreTexts

13.5: Flag Variables

  • Page ID
  • To store a true or false value, you need a boolean variable. You can create one like this:

    boolean flag;
    flag = true;
    boolean testResult = false;

    The first line is a variable declaration, the second is an assignment, and the third is both. Since relational operators evaluate to a boolean value, you can store the result of a comparison in a variable:

    boolean evenFlag = (n % 2 == 0);    // true if n is even
    boolean positiveFlag = (x > 0);     // true if x is positive

    The parentheses are unnecessary, but they make the code easier to read. A variable defined in this way is called a flag, because it signals or “flags” the presence or absence of a condition.

    You can use flag variables as part of a conditional statement later:

    if (evenFlag) {
        System.out.println("n was even when I checked it");

    Notice that you don’t have to write if (evenFlag == true). Since evenFlag is a boolean, it’s already a condition. Likewise, to check if a flag is false:

    if (!evenFlag) {
        System.out.println("n was odd when I checked it");
    • Was this article helpful?