Java if, if...else Statement

... // Do these statements before. 
 if (condition) {
 ... // Do this clause if the condition is true. 
} 
... // Do these statements after.


Example 1: Java if Statement

This displays one of two messages, depending on an input value.

class IfStatement { 
public static void main(String[] args) {
  if ((i >= 0) && (i <= 10)){ 
     System.out.println("i is an “ + “integer between 0 and 10"); 
  }
}
}


Flowchart representation of if statement :

The flow of execution in a program is sometimes represented by a flowchart. Flowcharts are sometimes a good way to outline the flow in a method, especially if it gets complex. They may be useful in user documentation, but most flow charting is done in quick sketches, which are thrown away once the program is written.



Nearest 'else' :

If you use braces, there is no problem with deciding which else goes with which if For example,
class IfElseDemo { public static void main(String[] args) { int testscore = 76; char grade; if (testscore >= 90) { grade = 'A'; } else if (testscore >= 80) { grade = 'B'; } else if (testscore >= 70) { grade = 'C'; } else if (testscore >= 60) { grade = 'D'; } else { grade = 'F'; } } }

Series of tests :

It is common to make a series of tests on a value, where the else part contains only another if statement. If you use indentation for the else part, it isn't easy to see that these are really a series of tests which are similar. It is better to write them at the same indentation level by writing the if on the same line as the else.


Example -- series of tests - cascading if :

This code is correctly indented, but ugly and hard to read. It also can go very far to the right if there are many tests.

if (score < 35) {
            g.setColor(Color.MAGENTA);
        } else {
            if (score < 50) {

                g.setColor(Color.RED);
            } else {
                if (score < 60) {
                    g.setColor(Color.ORANGE);
                } else {
                    if (score < 80) {
                        g.setColor(Color.YELLOW);
                    } else {
                        g.setColor(Color.GREEN);
                    }
                }
            }
        }

Previous Post Next Post