The Else Statement
The “else” statement can be combined with the “if” statement. The “else” statement specifies what to do if the “if” statement is not true. If you create an if/else block, then you are guaranteed that at least one part of it will execute. If the “if” part is true, it will be executed. If the “if” part is not true, then the “else” part will be executed. The general format of an if/else statement is as follows.
if( a==1 )
{
// this part will be executed if a is 1
}
else
{
// this part will be executed if a is not 1
}Now lets look at an example that uses an if/else statement. Listing 5.4 shows a modified version of the favorite color program we just examined. Listing 5.4 shows an example of using else.
Listing 5.4: Else Example (StringElse.java)
import java.io.*;
class StringElse
{
public static void main(String args[])
{
try
{
InputStreamReader inputStreamReader =
new InputStreamReader ( System.in );
BufferedReader in =
new BufferedReader ( inputStreamReader );
System.out.print(
"What is your favorite color? ");
String color = in.readLine();
if( color.equals("red") )
{
System.out.println(
"My favorite color is red too!");
}
else
{
System.out.println("I guess " + color +
" is okay, but I like red better.");
}
}
catch(IOException e)
{
}
}
}
This program will prompt the user for their favorite color. If the user chooses “red” as their favorite color, the program will agree with them. Otherwise the program will state that the user’s color is okay, but it prefers red. This is done with the else statement.












