Java
Learn Java in step-by-step lessons.
if / else statements
The if statement is used to execute a statement, or group of statments only under certain conditions.
There are several possible formats:
To execute just one statement when the Boolean expression is true:
if(boolean expression) statement;
To execute one or more statements when the Boolean expression is true use { and } around the statements:
if(boolean expression) {
statement;
statement;
...
}
There is an optional else that can be used when the Boolean expression is false:
if(boolean expression) statement;
else statement;
To execute one or more statements when the Boolean expression is either true or false use { and } around the statements:
if(boolean expression) {
statement;
statement;
...
}
else {
statement;
statement;
...
}
It is usually a good idea to put each statement on a separate line, but you can write if/else on one line:
if(grade<65) cout<<"fail"; else cout<<"pass";
Please study the material at each of the links below.
- Swap variables to put in order
- Calculate tip based on service
- Find a letter grade
- Using nested if/else to find letter grade
- Test if a number is a valid month
- Who gets a discount?
- Print season based on month
Glossary for ifelse lessonFull Glossary