Java Tutorials – Lesson 4: Conditional Statements (if…else if…else)

Google+ Pinterest LinkedIn Tumblr +

Conditional statements are an important part of programming. They are used to dictate the program flow (which linesof code are executed and which are not).

Conditional Statements

if Statement

The if statement is fairly self-explanatory. If the condition is true, then execute the following code.

Here is the syntax for the if statement:

If you have a single line of code to do within the if statement, you do not need brackets

If(True)

//Do this single line of code

If you have multiple lines of code to do within the if statement, you must use brackets.

if(True)

{

//Do these line(s) of code

//Do these line(s) of code

}

Code Example:

class IfStatement

{

public static void main(String args[])    //Main method (program always starts here)
{
boolean myBool = False;

int myInt = 334;

if(myBool || myInt < 500)//This is true, so the following lines within the {} are executed.

{

myInt = 501;

myBool = True;

}

//myBool is now true, and myInt is now 501.

if(myBool && myInt <500)//This statement is false, so the following lines of code within the {} are not executed

{

myBool = True;

myInt = myInt + 29;

}

System.out.println(“My Bool: ” + myBool + ” My Int: ” + myInt)//prints values of the variables, True and 501

}

}

if…else Statement

The if…else statement adds to the if statement. Here is the syntax and functionality:

if(conditional statement)

{

//Do this section of code if the conditional statement is TRUE

}

else

{

//Do this section of code if the above conditional statement is FALSE

}

if…else if…else Statement

The if…else statement adds to the if statement. Here is the syntax and functionality:

if(conditional statement 1)

{

//Do this section of code if conditional statement 1 is TRUE

}

else if(conditional statement 2)

{

//Do this section of code if conditional statement 2 is TRUE

}

else

{

//Do this section of code if conditional statement 1 and 2 is FALSE

}

It is important to note that only one of the code blocks will be executed, even if both conditional statement 1 and 2 are both TRUE. If both are TRUE, then the first code section will be completed, and program execution will continue after the else code block.

You can have as many else if’s following the first if as you want, and you do not have to put a final else statement if you do not require it.

if(s1)

else if(s2)

else if(s3)

else if(s4)

…etc

Share.

About Author

Leave A Reply