Zebra0.com

java ifelseJava

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.

  1. The syntax of if else

  2. Swap variables to put in order

  3. Calculate tip based on service

  4. Find a letter grade

  5. Using nested if/else to find letter grade

  6. Test if a number is a valid month

  7. Who gets a discount?

  8. Print season based on month

GlossaryGlossary for ifelse lesson
Full Glossary