ifelsepic

The "if ... else " Statements

Let's look at situations when the word "otherwise" can be used in your decision making!

if (test condition)  
{
      block of one;
      or more Java statements;
}
else
{
     block of one;
     or more Java statements;
}

If the test condition is TRUE, the block of statements following the "if" executes.  If the test condition FALSE, however, the block of statements following the "else" executes instead.  

blue a If you put a semicolon after the test condition in an "if - else" combination, an ERROR will occur on the else statement..

     Example:

// example of if ... else
System.out.println("Enter city name: ");
String city = reply.nextLine();
System.out.println("Enter population: ");
int population = reply.nextInt();

if (population >= 543876)
{
     System.out.println("According to the census, " +
                         city + " is one of \n the 100 largest cities.");
}
else
{
    System.out.println("According to the census, " +
                  city + " is not one of \n the 100 largest cities.");
}

 

divider
Return to Unit Menu |  JavaBitsNotebook.com | MathBits.com | Terms of Use  | JavaMathBits.com