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 if (condition) { do this clause if the condition is true } do these statements afterwards
or
do these statements if (condition) { do this clause if the condition is true } else { do this clause if the condition is false } do these statements afterwards
It is good programming style to always write the curly braces, {}
,
altho they are not needed if the clause contains only a single
statement.
true
or false
The value of condition must be true
or false
(ie, a boolean
value). It is often a comparison.
. . . if (marks < 60) { JOptionPane.showMessageDialog(null, "This is terrible"); } else { JOptionPane.showMessageDialog(null, "Not so bad"); } . . .
The code above will display one of two dialogs, depending on teh value of marks.