Go to Top

Friday, 25 March 2011

The If-Else Loop

                          This is a kind of loop in Java which is required to execute a command only if a condition is true. Its syntax is as follows :

if(condition)
{
  ----------
  ----------
}
 else
 {
  ----------
  ----------
}

                          If the condition is true, then Java will execute the commands following the if statement and neglect the else part, but if the condition is false, it will either execute the command following the else statement and will neglect the part following the if statement, or will execute no command if the else statement is not given, since it is not compulsory. But in some cases, it is very much necessary to give the else option, which will then return an "if without else" error in case if the else statement is absent. An example of its usage is given as follows :

if(n>10) (n is any number given by the user)
{
  System.out.println(n+" is not smaller than 10");
}
else
{
  System.out.println(n+" is smaller than 10");
}

(In case of a single statement, it is not necessary to give the opening and closing braces. If the braces are not found, then the statement just after the if or the else statement will be executed by Java)
                          

2 comments:

ShareThis