Conditional Statements in Java

Java No Comments

Conditional statements are used to compare two data types of values in Java. You can use if, if…else and switch statements for this purpose.

If and If…else

These statements compare values and follow the steps based on whether the comparison is true or false.

Example:

public class Main {
    public static void main(String[] args){
        int a = 1;
        int b = 2;
        if (a>b){
            System.out.println("a is greater");
        }else if(b>a){
            System.out.println("b is greater");
        }else{
            System.out.println("They are both equal");
        }
    }
}

Output

b is greater

Switch

The switch statement also compares values and follow the instructions based on when they are true.

Example

public class Main {
    public static void main(String[] args){
        int a = 1;
        switch(a){
            case 1:
                System.out.println("It is one");
                break;
            case 2:
                System.out.println("It is two");
                break;
            default:
                System.out.println("It is nothing");
                break;
        }
    }
}

Output:

It is one

Switch can compare byte, short, int and char, and in Java 7 string is also supported.

No Comments

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.