If-else Statement

if-else statement is extension of if statement. In if statement statements are executed on success of condition, if condition is false then nothing will happen. For example if we want to write a program that will check a number is odd or even, with if statement we can't handle both situation(odd and even). If-else allow us to write statement, which will be executed on failure of condition.


Syntax:

	if( condition_statement )
Statement_1;
else
Statement_2;

if condition specified is true then statement_1 will be executed. On the failure of condition Statement_2 will be executed. For single statement body no need to enclose statement in curly braces.


Syntax:

	if( condition_statement )
{
Statement_1;
Statement_2;
Statement_3;
}
else
{
Statement_4;
Statement_5;
}

All three statements will be executed if condition_statement is true. On failure statement 4 and 5 will execute. if statement following ';', considered without body or null body if statement.


Syntax:

	if( condition_statement ) ;
else
{
Statement_1;
}


Example:


	//file:ifelstate.java
//www.jgyan.com
class ifelstate
{
public static void main(String arg[])
{
int a=30;
if(a<20)// Single statement in body
System.out.println("a is less than 20");
else
System.out.prinltn("a is greater than 20");

if(a%2==0) // Body with curly braces.
{
System.out.println("a is even number");
}
else
{
System.out.println("a is odd number");
}

}
}
/*output
a is greater than 20
a is even number
*/