Home Java Java-tips Flow If if Statement - Overview

Ask Questions?

View Latest Questions

Advertisement


 
 

if Statement - Overview
Posted on: July 26, 2006 at 12:00 AM
The purpose of the if statement is to make decisions.

Java Notes

if Statement - Overview

Purpose

The purpose of the if statement is to make decisions, and execute different parts of your program depending on a boolean true/false value. About 99% of the flow decisions are made with if. [The other 1% of the decisions use the switch/case statement.]

General Forms

The if statement has this form:

Do these statements before.
if (condition) {
    Do this clause if the condition is true.
}
Do these statements after.

or

Do these statements before.
if (condition) {
    Do this clause if the condition is true
} else {
    Do this clause if the condition is false
}
Do these statements after.

Style. It is good programming style to always write the curly braces, {}, altho they are not needed if the clause contains only a single statement. There are two reasons this is good.

  • Reliability. When code is modified, the indentation is such a strong indicator of structure that the programmer may not notice that the addition of a statement at the "correct" indentation level really isn't included in the scope of the if statement. This is a suprisingly common error.
  • Readability. It is faster to read code with the braces because the reader doesn't have to keep in mind whether they are dealing with an un-braced single statement or a braced block.

Braces have been used in most language that have descended from Algol, including C, C++, Java, C# etc because the language designers want to make it easy for programmers in earlier languages to make the transition. Unfortunately, they are extremely error prone, and languages such as Visual Basic and Python have chosen better notation.

Condition is true or false

The value of condition must be true or false (a boolean value). It is often a comparison.

. . .
int    score;     // Integer score on test.
String scoreStr;  // Temporary String form of score input.
String comment;   // Message to the user.

scoreStr = JOptionPane.showInputDialog(null, "Your score?");
score = Integer.parseInt(scoreStr);

if (score < 60) {
    comment = "This is terrible";
} else {
    comment = "Not so bad";
}

JOptionPane.showMessageDialog(null, comment);
. . .

The code above will display one of two messages, depending on the value of score.

Copyleft 2005 Fred Swartz MIT License
Advertisement


DMCA.com