Introduction to Java: If Statements

Posted by Hayri Cicek on June 08, 2019


If statement is the most basic way of test a condition. With the if statement you test if a condition is true or false.

If Statement example:
Open your favorite code editor and type in the following:


1   public class IfStatementExampleOne {
2       public static void main(String[] args) {
3           String lang = "Kotlin";
4
5           if (!"Java".equals(lang)) {
6               System.out.println("The language is not java");
7           } 
8       }
9   }


On line 3 we declared a variable named lang which holds the string Kotlin.
On line 5 we check if the Java string is not equals to the variable lang then we print the message The language is not java.

Open your command line and type the following to compile the source code.

$ javac IfStatementExampleOne.java
Now type the following to run the app.

$ java IfStatementExampleOne

Output:
The language is not java

Nested If Statement
When an if statement is inside another if statement, then it's called nested if statement. Create a new file called NestedIfStatement.java and type in the following :

public class NestedIfStatement {
    public static void main(String[] args) {
        String lang = "Kotlin";

        if (!"Java".equals(lang)) {
            System.out.println("The language is not Java");

            if ("Kotlin".equals(lang)) {
                System.out.println("The language is Kotlin");
            }
        }
    }
}


Now compile the source code and then run it and you'll see the following output

The language is not Java
The language is Kotlin


If, else Statement
If the statement is not true then the statement inside else will be executed.
Create a new file called IfElseStatement.java and add the following :

public class IfElseStatement {
    public static void main(String[] args) {
        int num = 10;

        if (num == 5) {
            System.out.println("The number is 5");
        } else {
            System.out.println("The number is not 5");
        }
    }
}


Now compile the file using javac IfElseStatement.java and run it using java IfElseStatement.
You will see the following output :

The number is not 5

If, else if, else Statement
You can check multiple conditions using if-else-if statement.
Type in the following in a file called IfElseIfStatement.java :

public class IfElseIfStatement {
    public static void main(String[] args) {
        int num = 10;

        if (num == 5) {
            System.out.println("Number is 5");
        } else if (num == 10) {
            System.out.println("Number is 10");
        } else {
            System.out.println("Don't know what the number is");
        }
    }
}


You will see the following output :

Number is 10


Share this: