JRJC - How To do Conditional Branching

Brief note for C and C++ programmers

The if construct in Java is almost the same as in C and C++. The only difference is when testing for true or false. In C or C++, the expression had to evaluate to zero or non-zero. In Java, it must evaluate to a boolean true or false.

All about conditional branching for everybody else

The if construct is probably the most frequently used construct in any programming language. In Java, the structure looks like this:

    if ( Expression )
    {
        DoStuff
    }

And you have the option of adding an else clause:

    if ( Expression )
    {
        DoStuff
    }
    else
    {
        DoOtherStuff
    }

which can be compounded if you need it:

    if ( Expression )
    {
        DoStuff
    }
    else if ( AnotherExpression )
    {
        DoOtherStuff
    }
    else
    {
        DoYetOtherStuff
    }

DoStuff, DoOtherStuff and DoYetOtherStuff can be any Java commands and constructs you want.

Expression and AnotherExpression can be any Java expression that evaluates to a Java boolean value (true or false).

Example:


    if ( goatSize > 5 )
    {
        System.out.println("Dat's a mighty big goat you got der.");
    }
    else
    {
        System.out.println("Wut's wrong wit chyer goat der?");
    }

Look on page 71 of Just Java 2 for more information on the if construct.




© 2000 Paul Wheaton