Programming & Scripting Tutorials

Java: If and Else Statements



If statements



If statements check if something is true; Then if it is true it does whatever you specify, otherwise it does not do what you specified (or will do what is in the else statements).
Heres an example of an if statement:

int MyNumber = 1;

if(MyNumber == 1){
       System.out.println("MyNumber = 1!");
}

When you execute this program it would display "MyNumber = 1!", however if we changed MyNumber to a different value (not 0) then nothing would be displayed.

"MyNumber == 1" is a conditional statement, we can use different conditional operators to achieve different goals. Here is a list of some conditional operators:

"==" Equal To
">" Greater Than
"<" Less That
">=" Greater than or equal to
"<=" Less than or equal to
"!=" Not equal to


Else



You can also have an else statement (which comes off the if statement); This simply means that if the if statement is not true the content of the else statement will be executed.
For Example:

int MyNumber = 1;

if(MyNumber = 0){
       System.out.println("MyNumber = 0!");
} else {
       System.out.println("MyNumber does not equal 0!");
}

In this case "MyNumber does not equal 0!" would be displayed.


Else If



Else if statements are as they sound. If the main if statement isn't true, it will check the elseif statement, if the elseif isn't true it uses the else statement like so:

       int MyNumber = 1;
       if(MyNumber == 0){
           System.out.println("MyNumber = 0!");
       } else if(MyNumber == 1){
           System.out.println("MyNumber = 1!");
       } else {
           System.out.println("MyNumber doesn't equal zero or one!");
       }


You can have as many elseif statements as you like to an if statement.


Finally..



Finally don't forget that you can nest if, else and elseif statements. This means that you can have one or more if..elseif..else statements inside an if, elseif, or else statement.
You can even created extremely complex, confusing, long nested statements!

This Java tutorial was written by


Back to Java

Advertisement: