If Statement Introduction in Java

Purpose :
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 statement.]

 General Forms :
The if statement has this form, where condition is true or false.
... // Do these statements before.
 if (condition) {
   ... // Do this clause if the condition is true.
... // Do these statements after.

Example :
This displays one of two messages, depending on an input value.
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) {
        } else {
            if (score < 50) {

            } else {
                if (score < 60) {
                } else {
                    if (score < 80) {
                    } else {
Previous Post Next Post