The else statement allows us to do something if our test returns false.

  1. if (A==5) {
  2. System.out.println("equal");
  3. } else {
  4. System.out.println("Not equal");
  5. }

 

So now what we have is a decision. If the test A==5 is true, we display "equal". If the test A=5 is false, we will display "not equal". The else basically tells java that if the test is false then we must do something else.

Even more useful is the fact we can do further tests using the else statement.

  1. if (A==5) {
  2. System.out.println("equal to 5");
  3. } else if (A == 4) }
  4. System.out.println("equal to 4");
  5. else {
  6. System.out.println("not equal to 5 or 4");
  7. }

 

We can chain as many else if's together as we wish. A if statement allows us to run one block OR another but not both! This is fundamental to the way programming works and needs exploring.

next comparison operators >>

 

 
Basics
Menu
Search