Home

Conditionals

Sometimes, you'll want to execute some code only if a certain "test" is true. The way we do this is with an "if" statement. For example, this code will only print the message "I'm bigger than 5!" if the variable x has a value bigger than 5:

if(x > 5)
{
    println("I'm bigger than 5!");
}

You can also use an "else" which means "if the test is false," as follows:

if(x > 5)
{
    println("I'm bigger than 5!");
}
else
{
    println("Apparently I'm not bigger than 5...");
}

The "else" must appear immediately after the "if's" closing brace.

Nested conditionals

if(x < 5)
{
    if(x < 0)
    {
        println("x is less than 0!");
    }
    else
    {
        println("x is less than 5 but not less than 0!");
    }
}
else
{
    println("x is not less than 5!");
}

Series of if/else's

It is common practice to check a series of conditions, where you only expect one of them to be true:

if(x == 0)
{
    // do stuff...
}
else if(x == 1)
{
    // do stuff...
}
else if(x == 2)
{
    // do stuff...
}
else
{
    // fallback...
}

More examples of "tests"

More interesting conditionals may involve the following boolean operators (assuming p and q are bool variables and x is an int variable). Refer to the variables and types video.

CSE 1211 material by Joshua Eckroth is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License. Source code for this website available at GitHub.