Saturday 15 April 2017

The if statement in Java




if statement in Java

The if statements is the basic flow control statement. It is used to select between two alternatives. In this sense, we use if statement to make decisions in our code based in some criteria. We decide whether to execute a section of code based on test condition that will be either true or false the general form of if is:

 if (condition)
 {
   Statement; // This block is executed
   Statement; //if condition is true
 }

If the condition is true, the statement block will be executed otherwise the statement block will be skipped.

Here is an example,

PassTest.java

// This is the PassTest program in Java

 class PassTest
 {

   public static void main (String args[])
   {
   int testScore=83;

    if (testScore>=50)
   {
     System.out.println("Passed ");
     }
   }

 }

In the above program, value of the integer variable testScore is 83. Since the condition testScore>=50 evaluates to true, System.out.println(“Passed”); will get executed. So will see Passed on the screen.
  Now what happen if the condition is not true? You will see nothing. Is not a bit odd? There must be a way to do something if the condition is false.
 Here is the answer. Another of if statement is given bellow:

 if (condition)
 {
  Statement; // This block is executed
  Statement; //if condition is true
 }
 else
 {
  Statement; // This block is executed
  Statement; //if condition is false
 }

The else part will be executed if the condition become false. We are modifying the above program as below to see this fact:

// This is the LPassTest program in Java

 class LPassTest
 {

   public static void main (String args[])
   {
   int testScore=43;

    if (testScore>=50)
    {
     System.out.println("Passed ");// this will not print
    }
    else
    {
     System.out.println("Failed ");//you will see this
    }

   }

 }







 Next Topic Shahbaz

0 comments:

Post a Comment

Powered by Blogger.

Stats