Java Reference
In-Depth Information
The if/else Statement
The if statement is a fundamental control statement that allows Java to make deci‐
sions or, more precisely, to execute statements conditionally. The if statement has
an associated expression and statement. If the expression evaluates to true , the
interpreter executes the statement. If the expression evaluates to false , the inter‐
preter skips the statement.
Java allows the expression to be of the wrapper type Boolean
instead of the primitive type boolean . In this case, the wrap‐
per object is automatically unboxed.
Here is an example if statement:
if ( username == null ) // If username is null,
username = "John Doe" ; // use a default value
Although they look extraneous, the parentheses around the expression are a
required part of the syntax for the if statement. As we already saw, a block of state‐
ments enclosed in curly braces is itself a statement, so we can write if statements
that look like this as well:
if (( address == null ) || ( address . equals ( "" ))) {
address = "[undefined]" ;
System . out . println ( "WARNING: no address specified." );
An if statement can include an optional else keyword that is followed by a second
statement. In this form of the statement, the expression is evaluated, and, if it is
true , the first statement is executed. Otherwise, the second statement is executed.
For example:
if ( username != null )
System . out . println ( "Hello " + username );
else {
username = askQuestion ( "What is your name?" );
System . out . println ( "Hello " + username + ". Welcome!" );
When you use nested if/else statements, some caution is required to ensure that
the else clause goes with the appropriate if statement. Consider the following
if ( i == j )
if ( j == k )
System . out . println ( "i equals k" );
System . out . println ( "i doesn't equal j" ); // WRONG!!
Search WWH ::

Custom Search