Friday, November 15, 2013

Decision making statements in Java

There are two types of decision making statements in Java. They are:
  1. if statements
  2. switch statements
if Statement: An if statement consists of a Boolean expression followed by one or more statements.
Syntax:
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}

If the boolean expression evaluates to true then the block of code inside the if statement will be executed. If not the first set of code after the end of the if statement will be executed.

Example:
public class Test
{
public static void main(String args[])
{
int x = 10; if( x < 20 )
{
System.out.print("This is if statement");
}
}
}


if...else Statement
An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
Syntax:
if(Boolean_expression)
{
//Executes when the Boolean expression is true
}
Else
{
//Executes when the Boolean expression is false
}

Example:
public class Test
{
public static void main(String args[])
{
int x = 30;
if( x < 20 )
{
System.out.print("This is if statement");
}
Else
{
System.out.print("This is else statement");
}
}
}

No comments:

Post a Comment