AP Computer Science Java: Lesson 2.1
Conditional Statements - The If Statement


Lesson 2.1 - If Statements

Purpose: To learn how write Java if statements

Conditional Statements
The format of an if statement:

   if(condition)
   {
      list of statements...
   }


The "list of statements" will only be performed if the condition is TRUE. Also note that the "list of statements" can be one or more statements. Each individual statement must be terminated by a semi-colon. However, THERE IS NO SEMICOLON AFTER THE PARENTHESES OF THE CONDITION! Doing so terminates the connection between the if and the statements in the braces. Take care not to do this!

The braces used are actually only necessary if there is more than one statement to be perfromed if the condition is true. If there are no braces, only one statement is considered to be tied to the if. Let's look at some examples.

   if(x < 10)
   {
       System.out.println("Single-digit number");
   }

is equivalent to

   if(x < 10)
      System.out.println("Single-digit number");

or even

   if(x < 10) System.out.println("Single-digit number");


But the two following are NOT equivalent:

   if(x < 10)
   {
       System.out.println("Single-digit number");
       System.out.println(x);
   }

   if(x < 10)
       System.out.println("Single-digit number");
       System.out.println(x);

In the first if, both SOPln statements will only perform if x<10. In the second, only the first SOPln statement is tied to the if. The second one will perform no matter what the result of the condtion is. Indentation does not determine whether a statement is connected to an if, braces do.

In closing, while it is not necessary to put braces for one statement, programmers tend to do so as a good practice. One advantage is not having to remember them later when another statement is added to the if block.

© DanShuster.com