Tuesday, 9 June 2015

IF Control Statement

Syntax of IF statement


 

 

 


if(expr) statement;

expr is any expression that evaluates to a boolean value. If expr is evaluated as true, the statement will be executed otherwise, the statement is bypassed and the line of code following the if is executed.   

The expression inside if compares one value with another by using relational operators. Below table lists the java relational operators. It test relationship between two operands where operands can be expression or value. It returns boolean value. 

Relational Operators In Java

 Operator
Meaning 
Example 
 ==
Equals 
a == b 
 !=
Not equals 
a != b 
 >
Greater than 
a > b 
 <  
Less than 
a < b 
 >= 
Greater than or equals 
a >= b 
 <= 
Less than or equals 
a <= b 


Examples of If Statement

Example 1 : Program that displays a message based on condition checking

class IfStateDemo
{
  public static void main(String args[])
  {
if(args.length == 0)
{
System.out.println("No arguments are passed to the command line.");
}
  }
}

//Call application from command line
java IfStateDemo 

Output
No arguments are passed to the command line.

Example 2 : Program that compares 2 numbers and displays greatest

class IfStateDemo
{
  public static void main(String args[])
  {
int num1 = 10;
int num2 = 15;
if(num1 > num2)
{
System.out.println("Number1 having value " + num1 + " is greater than number2 having value " + num2);
}
if(num2 > num1)
{
System.out.println("Number2 having value " + num2 + " is greater than number1 having value " + num1);
}
  }
}

No comments:

Post a Comment