Logo 
Search:

Java Articles

Submit Article
Home » Articles » Java » FundamentalRSS Feeds

IF Control Statement

Posted By: Daniel Watson     Category: Java     Views: 5336

This article explains about control statement IF in java with examples.

IF statement allows your program to conditionally execute a statement. It is one of java's selection statements and also called conditional statement. Selection statements make decisions based upon the outcome of some condition. 

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);
}
  }
}

Output
Number2 having value 15 is greater than number1 having value 10
  
Share: 

 
 

Didn't find what you were looking for? Find more on IF Control Statement Or get search suggestion and latest updates.

Daniel Watson
Daniel Watson author of IF Control Statement is from Los Angeles, United States.
 
View All Articles

 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
No Comment Found, Be the First to post comment!