Allen is a published fiction and non-fiction writer working on his second novel. He currently resides in Hanoi, Vietnam where he is traveling around SE Asia. He is an avid reader and lifelong geek interested in fiction, philosophy, and technology. Allen is a DZone Zone Leader and has posted 285 posts at DZone. You can read more from them at their website. View Full User Profile

OCA Java 7: The if and if-else Constructs

09.06.2012
| 8882 views |
  • submit to reddit
Editor's Note: This post is a free chapter from the book from Manning Publications "In the OCA Java SE 7 programmer certification guide" by Mala Gupta


In this article, I'll cover if and if-else constructs. We'll examine what happens when these constructs are used with and without curly braces {}. We'll also cover nested if and if-else constructs.

The if construct and its flavors

An if construct enables you to execute a set of statements in your code based on the result of a condition. This condition must always evaluate to a boolean or a Boolean value.  You can specify a set of statements to execute when this condition evaluates to true or false. (In many Java books, you'll notice that the terms constructs and statements are used interchangeably.) Figure 1 shows multiple flavors of the if statement with their corresponding representations.

  • if                    
  • if-else               
  • if-else-if-else              

 

Figure 1 Multiple flavors of if statement: if, if-else, and if-else-if

In figure 1, condition1 and condition2 refer to a variable or an expression that must evaluate to boolean or Boolean value. statement1, statement2, and statement3 refer to a single line of code or a code block. Because the Boolean wrapper class isn't covered in the OCA Java SE 7 Programmer I exam, we won't cover it here. We'll work with only the boolean data type.

Exam Tip: then isn't a keyword in Java and isn't supposed to be used with the if statement.

Let's look at the use of some flavors by first defining a set of variables: score, result, name, and file, as follows:

int score = 100; 
String result = "";
String name = "Lion";
java.io.File file = new java.io.File("F");

Figure 2 shows the use of if, if-else, and if-else-if-else constructs and compares them by showing the code side by side.

 

Figure 2 Multiple flavors of if statements implemented using code

Let's quickly go through the code used in above if, if-else, and if-else-if-else statements. In the following example code, if condition name.equals("Lion") evaluates to true, a value of 200 is assigned to the variable score:

if (name.equals("Lion"))	#A
   score = 200;		        #A

#A Example of if construct

In the following example, if condition name.equals("Lion") evaluates to true, a value of 200 is assigned to the variable score. If this condition were to evaluate to false, a value of 300 is assigned to the variable score:

if (name.equals("Lion"))		#A
     score = 200; 			#A
else					#A
     score = 300;			#A

#A Example of if else construct

In the following example, if score is equal to 100, the variable result is assigned a value of A. If score is equal to 50, the variable result is assigned a value of B. If the score is equal to 10, the variable result is assigned a value of C. If score doesn't match either of 100, 50, or 10, a value of F is assigned to the variable result. An if-else-if-else construct may use different conditions for all its if constructs:

if (score == 100)		#A
	result = "A";
else if (score == 50)	        #B
	result = "B";
else if (score == 10)	        #C
	result = "C";
else				#D
     result = "F";

#A Condition 1 -> score == 100

#B Condition 2 -> score == 50

#C Condition 3 -> score == 10

#D If none of previous conditions evaluate to true, execute this else

Figure 3 shows the previous code.

 

Figure 3 The execution of the if-else-if-else code

Figure 3 makes clear multiple points:

  • The last else statement is part of the last if construct and not any of the if constructs before it.
  • The if-else-if-else is an if-else construct, where its else part defines another if construct. A few other programming languages, such as VB and C#, use if-elsif and if-elseif (without space) constructs to define if-else-if constructs. If you've programmed with any of these languages, note the difference is with respect to Java. The following code is equal to the previous code:
if (score == 100)
	result = "A";
else
	if (score == 50)
		result = "B";
	else
		if (score == 10)
			result = "C";
		else
			result="F";

Again, note that none of the previous if constructs use then to define the code to execute if a condition evaluates to true.  As mentioned previously, unlike other programming languages, then isn't a keyword in Java and isn't used with the if construct.

 Exam Tip The if-else-if-else is an if-else construct, where else part defines another if construct.

The boolean expression used as a condition for if construct can also include assignment operation.

Missing else blocks

What happens if you don't define the else statements for an if construct? It's acceptable to define one course of action for an if construct, as follows (omitting the else part):

boolean testValue = false;
if (testValue == true)				
	System.out.println("value is true");

But you can't define the else part for an if construct, skipping the if code block. The following code won't compile:

boolean testValue = false;
if (testValue == true)				
else                                              #A
	System.out.println("value is false");	

#A This won't compile

What follows is another interesting and bizarre piece of code:

int score = 100; 
if((score=score+10) > 110);		#1

#1 Missing then or else part

Line #1 is a valid line of code, even if it doesn't define both the then and else part of the if statement. In this case, if condition evaluates and that's it. The if construct doesn't define any code that should execute based on the result of this condition.

Note if(testValue==true) is same as using if(testValue). Similarly, if(testValue==false) is same as using if(!testValue).

Implications of presence and absence of {} in if-else constructs

You can execute a single statement or a block of statements, when if condition evaluates to true or false values. A block of statement is marked by enclosing single or multiple statements within a pair of curly braces ({}). Examine the following code:

String name = "Lion";
int score = 100;
if (name.equals("Lion"))  
	score = 200;

What happens if you want to execute another line of code, if value of variable name is equal to Lion? Is the following code correct?

String name = "Lion";
int score = 100;
if (name.equals("Lion"))
	score = 200;
	name = "Larry";		#1

#1 Set name to Larry

Exam Tip In the exam, watch out for code similar to the above mentioned if construct that uses misleading indentation. In the absence of a code block definition (marked with a pair of {}), only the statement following the if construct forms its part.

What happens to the same code if you define an else part for your if construct as follows:

String name = "Lion";
int score = 100;
if (name.equals("Lion"))
	score = 200;
	name = "Larry";	#A
else				
	score = 129;

#A This statement isn't part of the if construct

In this case, the previous code won't compile. The compiler will report that the else part is defined without an if statement. If this leaves you confused, examine the following code, which is indented in order to emphasize the fact that line name = "Larry" isn't part of the else construct:

String name = "Lion";
int score = 100;
if (name.equals ("Lion"))
	score = 200;

name = "Larry";		#A 

else				#B
	score = 129;

#A Right indentation to emphasize that this statement isn't part of the if construct

#B else seems to be defined without a preceding if construct

If you want to execute multiple statements for if construct, you should define them within a block of code. You can do so by defining all this code within curly braces ({}). To follow is an example:

String name = "Lion";
int score = 100;
if (name.equals("Lion")) {   #A 
	score = 200;		   #B
	name = "Larry";	   #B
}                             #C
else				
	score = 129;

#A Start of code block

#B Statements to execute if (name.equals("Lion")) evaluates to true

#C End of code block

Similarly, you may define multiple lines of code for the else part (incorrectly) as follows:

String name = "Lion";
if (name.equals("Lion"))
	System.out.println("Lion");
else
	System.out.println("Not a Lion");
	System.out.println("Again, not a Lion");        #1

#1 Not part of else construct. Will execute irrespective of the value of variable name

The output of the above code is as follows:

Lion
Again, not a Lion

Though code on line #1 seems to execute only if value of variable name matches with value Lion, this is not the case. It is indented incorrectly to trick you into believing that it is a part of the else block. The above code is same as the following code (with correct indentation):

String name = "Lion";
if (name.equals("Lion"))
	System.out.println("Lion");
else
	System.out.println("Not a Lion");
System.out.println("Again, not a Lion");        #1

#1 Not part of else construct. Will execute irrespective of the value of variable name

If you wish to execute the last two statements in the previous code, only if the if condition evaluates to false, you can do so by using {}:

String name = "Lion";
if (name.equals("Lion"))
	System.out.println("Lion");
else {
	System.out.println("Not a Lion");
	System.out.println("Again, not a Lion");        #1
   }

#1 Now part of else construct. Will execute only when if condition evaluates to false

You can define another statement, construct or loop, to execute for an if condition, without using {}, as follows:

String name = "Lion";
if (name.equals("Lion"))                 #A
	for (int i = 0; i < 3; ++i)          #B
		System.out.println(i);      #C

#A if condition

#B for loop is a single construct that will execute if name.equals("Lion") evaluates to true

#C This code is part of the for loop defined at previous line

System.out.println(i) is part of the for loop, and not an unrelated statement that follows the for loop. So this code is correct and gives the following output:

0
1
2

Appropriate vs. inappropriate expressions passed as arguments to an if statement

The result of an expression used in an if construct must evaluate to a boolean or Boolean value. Given the following definition of variables:

int score = 100;
boolean allow = false;
String name = "Lion"; 

Up next are examples of some of the valid expressions that can be passed on to an if construct. Note that using == is not a good practice to compare two String objects for equality. The correct way to compare two String objects is to use equals method from the String class. However, comparing two String values using == is a valid expression that returns a boolean value and may also be used in the exam:

(score == 100)	    #A
(name == "Lio")	    #B
(score <= 100 || allow) #C
(allow)		    #D

#A Evaluates to true

#B Evaluates to false

#C Evaluates to true

#D Evaluates to false

Now comes the tricky part of passing an assignment operation to an if construct. What do you think is the output of the following code?

boolean allow = false;
if (allow = true)                           #A
	System.out.println("value is true");
else
	System.out.println("value is false");

#A This is assignment, not comparison

You may think that because the value of the boolean variable allow is set to false, the previous code output's value is false. Revisit the code and notice that assignment operation allow = true assigns the value true to the boolean variable allow. Further, its result is also a boolean value, which makes it eligible to be passed on as an argument to the if construct,

Although the previous code has no syntactical errors, it's a logical error-an error in the program logic. The correct code to compare a boolean variable with a boolean literal value should be defined as follows:

boolean allow = false;
if (allow == true)				#A
	System.out.println("value is true");
else
	System.out.println("value is false");

#A This is comparison

Exam Tip Watch out for the code in the exam that uses the assignment operator (=) to compare a boolean value in the if condition. It won't compare the boolean value; it'll assign a value to it. The correct operator to compare a boolean value is equality operator (==).

Nested if constructs

A nested if construct is an if construct defined within another if construct. Theoretically, you don't have a limit on the levels of nested if and if-else constructs. Whenever you come across nested if and if-else constructs, you need to be careful about determining the else part of an if statement. If this statement doesn't make a lot of sense, take a look at the following code and determine its output:

int score = 110;
if (score > 200)		#1
	if (score <400)	#2
		if (score > 300)
			System.out.println(1);
		else
			System.out.println(2);
else					             #3
	System.out.println(3);                     #3

#1 if (score>200)

#2 if (score<400)

#3 To which if does this else belongs?

Based on the way the code is indented, you may believe that else at #3 belongs to the if defined at #1. But it belongs to the if defined at #2. To follow is the code with the correct indentation:

int score = 110;
if (score > 200)		
	if (score <400)	
		if (score > 300)
			System.out.println(1);
		else
			System.out.println(2);
else					#A
		System.out.println(3);	#A

#A This else belongs to the if with condition (score<400)

Next, you need to understand how to do the following:

  • How to define an else for an outer if, other than the one that it'll be assigned to by default
  • How to determine to which if does an else belong in nested if constructs

Both of these tasks are simple. Let's start with the first one.

How to define an else for an outer if other than the one that it'll be assigned to by default

The key point is to use curly braces, as follows:

int score = 110;
if (score > 200) {		#1
	if (score <400)		
		if (score > 300)
			System.out.println(1);
		else
			System.out.println(2);
}					#2
else					#3
	System.out.println(3);	#3

#1 Start if construct for score  > 200

#2 End if construct for score > 200

#3 else for score > 200

The curly braces at #1 and #2 mark the start and the end of the if condition (score>200) defined at #1. Hence, the else at #3 that follows #2 belongs to the if defined at #1.

How to determine to which if an else belongs in nested if constructs

If code uses curly braces to mark the start and end of the territory of an if or else construct, it can be simple, as mentioned in the previous section, "How to define an else for an outer if than the one that it'll be assigned to by default." When the if constructs don't use curly braces, don't get confused by the code indentation. Try to match all if with their corresponding else in the following poorly indented code:

if (score > 200)
if (score <400) 
if (score > 300)
	System.out.println(1);
else
	System.out.println(2);
else
	System.out.println(3);

Start working inside out, with the innermost if-else statement, matching else with its nearest unmatched if statement. Figure 4 shows how to match the if-else pairs for the previous code, marked with 1, 2, and 3.

 

Figure 4 Matching if-else pairs for poorly indented code

Summary

We covered the different flavors of the if construct. You saw what happens when these constructs are used with and without curly braces {}. We also covered nested if and if-else constructs. The humble if-else construct can virtually define any set of simple or complicated conditions.

 

OCA Java SE 7 Programmer I Certification Guide

By Mala Gupta

In the OCA Java SE 7 programmer exam, you'll be asked you'll be asked how to define and control the flow in your code. In this article, based on chapter 4 of OCA Java SE 7 Programmer I Certification Guide, author Mala Gupta How show you to use if, if-else, if-else-if-else and nested if constructs and the difference when these if constructs are used with and without curly braces {}.

Here are some other Manning titles you might be interested in:

Unit Testing in Java

Lasse Koskela

Making Java Groovy

Kenneth Kousen

Play for Java

Nicolas Leroux and Sietse de Kaper