Varieties of if Statements

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

Answer:

Surprisingly (unless you have been paying close attention), the output is:

No cookie for you.

Varieties of if Statements

Do not write a program that depends on the result of == with floating point.

There are many ways to use if statements. They can be used with one or two branches, and each branch can include one or more statements. The table that shows these variations.

The boolean expression in each of these varieties evaluates to true or false. Boolean expressions come in a variety of forms, which allow you to carefully state the conditions under which each branch will execute (see the next chapter for this).

Varieties of if Statements
 
if ( booleanExpression )
  statement;
if ( booleanExpression )
{
  one or more statements
}
if ( booleanExpression )
  statement;
else 
  statement;
if ( booleanExpression )
{
  one or more statements
}
else 
{
  one or more statements
}
if ( booleanExpression )
  statement;
else 
{
  one or more statements
}
if ( booleanExpression )
{
  one or more statements
}
else 
  statement;

The style of indenting used in the above leads to fewer errors than other styles you may have seen. An experiment with a group of professional programmers found this to be true. Of course, the Java compiler ignores indenting and blank lines. Use this style unless there is a good reason not to (such as an employer or instructor that requires a different style).

No matter which style you use, be consistent. Use the same number of spaces for indenting. (I use two spaces. Many people prefer four.) Soon you will be able to visuallize the logic of your programs. Programming and error catching will be easier.

QUESTION 6:

Is the following a correct if statement?

if ( booleanExpression ){
    one or more statements
}else {
    one or more statements }