Saturday, 2 February 2013

if and if-else control statements in java

The most common Control Statements in Java

Control Statement if and if.. else

The if Statement:


In Java if statement is most widely used. The if statement is control statement which helps programmers in decision making. The if statement uses boolean expression in making decision whether a particular statement would execute or not. This is a control statement to execute a single statement or a block of code, when the given condition is true and if it is false then it skips if block and rest code of program is executed. 


Let’s look at syntax of if statement:

if(condition)
{
     //code
}
//rest of the code


Example for simple if statement

Class IfSample
{
     public static void main(String args[])
     {
          int x,y;
          x=10;
          y=20;
          if(x<y)
          System.out.println(“x is less than y”);
     }
}

Control Flow of If Statement


         
if Statement Control Flow Diagram


















The if-else Statement:


If the Boolean expression is true if-code gets executed. If boolean-expression is false else-code gets executed. In this decision making statements generally either of the block gets executed whether its if-code or else-code, after either execution rest-code gets executed. The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false.

Syntax of the if-else statement

if(condition)
{
     //code
}
else
{
     //code
}
//rest of the code

Example for simple if-else statement


class IfElseDemo 
{
     public static void main(String[] args) 
     {
          int testscore = 76;
          char grade;           if (testscore >= 90) 
          {
               grade = 'A';
          } 
          else if (testscore >= 80) 
          {
             grade = 'B';
          } 
          else if (testscore >= 70) 
          {
             grade = 'C';
          }
          else if (testscore >= 60) 
          {
             grade = 'D';
          } 
           else 
          {
             grade = 'F';
           }
          System.out.println("Grade = " + grade);
     }
}

    
The output from the program is:

Grade = C

Control Flow of If Statement


if-else Control Flow Diagram





No comments :

Post a Comment