MathBits.com
Return to Unit Menu | Java Main Page | MathBits.com | Terms of Use  

   The "if" Statement

It's time to make decisions using the relational operators.

The "if" expression is called a conditional statement (decision statement) because it tests a relationship by using the relational operators.  Based upon the result of the comparison, decisions are made as to which statement(s) the program will execute next. 

if (test condition)  
{
      block of one;
      or more C++ statements;
}

blue a

If you put a semicolon after the test condition, the "if" statement will STOP.  The block will not be executed.

The test condition can be any relational comparison (or logically TRUE) statement and must be enclosed in parentheses.  The block of statements is enclosed in braces and indented for readability.  The braces are NOT required if only ONE statement follows the "if", but it is a good idea to include them.

The block executes only if the test condition is TRUE.  If the test condition is FALSE, the block is ignored and execution continues to the next statement following the block.

 

Keep in mind:
if (a = 3)   will cause an ERROR.  The condition a = 3 is an assignment statement, whereas test conditions are looking for Boolean true or false expressions.

if (a = = 3)   is a Boolean test condition.  This statement is true ONLY if the value stored in a is the number 3.

 

    Examples:

// using a character literal
if (grade = = 'A')
{
   System.out.println("Frig Grade");
}

 

// logically true
if (true)
{
     System.out.println("Way to go!");
     System.out.print("The x is true!");
}
// using two variables
if(enemyCount< heroCount)
{
     System.out.print("Good wins!");
}
// using a calculation
if (cost * number  = = paycheck)
{
     inventory = 0;
}

 

 


Return to Unit Menu | Java Main Page | MathBits.com | Terms of Use