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.]
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.
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.
true or falseThe 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.