Monday 1 August 2011

The if decision structure


The if statement evaluates a condition and if the result is true then it runs the line of code that follows it. Here is an example of how to test if the value of a variable called I is equal to 5 :
public class Decisions
{
               public static void main( String [ ] args )

               {
               int i = 5 ;
               if ( i == 5)
                 System.out.println( “ I is equal to 5 “ );
               }
}
If you change i to 4 and run this program again you will see that no message is printed.
else
               we know that if the condition is true then the code directly afer the if statement is run. You can run code for when the condition is false by using the else statement

public class Decisions
{
               public static void main ( String [ ] args )

               {

               int i = 4 ;
               if ( i = = 5 )

               System.out.println ( “ i is equal to 5 “);

               else

               System.out.println( “i is not equal to 5 “ );
}
}

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More