Wednesday, June 27, 2007

Chapter 5 - Flow Control and Exception Handling

Chapter 5: Flow Control and Exception Handling

Objectives

This chapter helps you to prepare for the exam by covering the following objectives:

Know which statements are supported by Java and how each statement works.

.
You must know what statements Java supports and how they work to be able to program in
Java. The exam will contain questions that will require you to determine if a program or block
of statements uses correct statement syntax.
Know how to analyze a sequence of statements, identify the flow of control, and determine the
results of statement execution.

.
Several exam questions require you to analyze a block of code and predict the output
displayed by the code. You may also be required to identify specific points within the code
that cause a particular action to occur.
Know how exceptions are handled and be able to trace through exception processing.

.
Being able to handle exceptions is an important part of Java programming. You'll need to
know how to throw and catch exceptions in order to correctly answer some exam questions.
You'll also need to know how the finally clause of the try-catch statement works.
- 74



Study Strategies

As you read through this chapter, concentrate on the following key items:

.
What statements are supported by Java and how each statement works
.
How to trace through statement execution
.
How exceptions are thrown and caught
.. How the try-catch-finally statement works
Chapter Introduction

This chapter covers Java statements. If you've written a few Java programs, then you're probably
familiar with most of the statements covered in this chapter. Most of the material that is presented will
seem pretty basic. However, pay attention just in case there is a detail or two that you're not familiar
with. This chapter will fill in any gaps that you you might have. You'll see plenty of questions on the
exam that will require you to analyze a small program or a block of Java code and determine the output
that it will produce. The review questions and exam questions at the end of this chapter will test your
understanding of Java statements and will give you an idea of the types of questions that you may see
on the exam.

Java Statements

Java provides a wide range of programming statements that can be used to create structured object-
oriented programs. These statements allow you to evaluate expressions, invoke methods, shape and
control the flow of program execution, and throw and handle exceptions. Table 5.1 provides a summary
of the programming statements that are provided by Java. You covered assignments in Chapter 3,
"Operators and Assignments," and declarations in Chapter 4, "Declarations and Access Control." This
chapter is limited to those statements that affect the flow of program execution.

Table 5.1: Java Statements

Statement
empty
block
declaration
labeled
assignment
invocation
return
object creation
if
Description
A statement consisting of just
";" that performs no operation.
A group of statements
enclosed by { and }. The
statement block is treated as a
single statement when used
with selection, iteration, and
other statements.
Declares a variable as being of
a particular type and optionally
assigns a value to the variable.
Statements may be labeled by
preceding them with identifier:.
Evaluates an expression and
assigns a value or object
reference to a variable.
Invokes a method of an object.
System.out.println("Theend!");
Returns a value from a method
invocation.
Creates a new object of a
particular type
Selects among two alternative
Example
;
{
x += y;
if(x==100)
return y;
}
String s =
"abcd";
loopA: for(;;) {}
c = (a*a +
b*b)/2;
return x*x
+ y*y;
new
Application();
if(x > y)

- 75



switch
for
Statement
while
do
break
continue
try-catch-finally
throw
synchronized
courses of execution.
Selects among several
alternative courses of
execution.
Iterates a variable over a
range of values and repeatedly
executes a statement or
statement block.
Description
Executes a statement or
statement block while a
condition is true.
Executes a statement or
statement block until a
condition is false.
Transfers control to a labeled
statement or out of an
enclosing statement.
Continues execution of a loop
the next iteration.
Catches and processes
exceptions that occur within
the execution of a statement
block.
Throws an exception.
Acquires a lock on an object
and executes a statement
block.
++y;
else ++x;
switch (n) {
case 1:
case 2:
case 3:
default:
}
for(inti=0;i<100;
++i) {}
Example
while }
(!finished)
{}
do {
} while(!finished);
for (inti=0;i<100;++i)
{ if(x[i] ==
0) break;
}
for (inti=0;i<100;++i)
{ if(i%10 ==
0) continue;}
try {}
catch
(Exception e)
{} finally {}
throw new
MyException();
synchronized(obj) {
obj.setProperty(x);
}

Most, but not all, of the statements shown in Table 5.1, are covered in this chapter. The following list
describes those that are not covered in this chapter:

.
The empty statement is trivial and is not addressed further.
.
The block statement is not a unique statement in and of itself. It consists of a semicolon-
separated list (possible empty) of statements enclosed by { and }.
.
Statement labels are covered in this chapter with the break statement.
.
Assignments are covered in Chapter 3, "Operators and Assignments."
.
Declarations, method invocations, the return statement, and object creation are covered in
Chapter 4, "Declarations and Access Control."
.. The synchronized statement is covered in Chapter 8, "Threads."
All the other statements shown in Table 5.1 are covered in the following sections.
Selection Statements

Java supports two statements, if and switch, that support the selection of alternative courses of
execution. The if statement is used to select among two alternatives. The switch statement can be
used to select among multiple courses of execution.

- 76



The if Statement

The Java if statement is similar to that of C and C++. Its syntax is as follows:
if (boolean expression) statement1;


or
if (boolean expression) statement1; else statement2;
In the first form, if the boolean expression evaluates to true, statement1 is executed.
Otherwise, execution continues with the next statement following the if statement.
In the second form, if the boolean expression evalautes to true statement1 is executed.
Otherwise, statement2 is executed.
In both forms of the if statement a statement block may be substituted for statement1 and
statement2. if statements may be nested. This is accomplished when statement1 or statement2
are also if statements.


The switch Statement

The switch statement is also taken from C and C++. Its syntax follows:
switch(int expression)
{
case n1:


statements
case n2:


statements
.
.
.
case nm:


statements
default:
statements
}
The int expression must evaluate to a int value or a value that can be promoted to an int (that is
byte, char, or short). The values following the case labels (n1, n2,…nm) must be constant
expressions that can be fully evaluated by the compiler. The default label is optional.
The switch statement is executed as follows:

1.
The int is evaluated. If it matches any ni of the n1, n2, …, nm then statement
execution transfers to the statement following case ni.
2.
If the int expression does not match any of the n1, n2, …nm and a default label is
supplied, then statement execution transfers to the statement following default.
3.
If neither of the above two cases are satisfied, then statement execution continues with
the next statement following the switch statement.
The cases of the switch statement are not mutually exclusive. For example, consider the program
shown in Listing 5.1. It displays the following output:

3
4
5
6
7
default


In order to ensure that only one case of a switch statement is executed, you need to use the break
statement. The break statement is covered in the next section.

Listing 5.1: Switch1.java—The switch Statement


- 77



class Switch1 {

public static void main(String[] args) {
int n = 3;
switch(n) {

case 1:
System.out.println(1);
case 2:
System.out.println(2);
case 3:
System.out.println(3);
case 4:
System.out.println(4);
case 5:
System.out.println(5);
case 6:
System.out.println(6);
case 7:
System.out.println(7);
default:
System.out.println("default");
}
}

}
The break Statement

The break statement is used to transfer execution out of an enclosing statement. It may be used with
or without a label. (A label consists of an identifier, followed by a colon.) When it is used without a label,
it causes execution control to transfer out of the innermost switch, for, do, or while statement
enclosing the break statement. When used with a label, the break statement transfers control out of
any enclosing statement with a matching label.

Note Labels Two or more statements may have the same label, provided that one

statement is not enclosed by the other.
Listing 5.2 shows how the break statement is used to ensure that only a single case of a switch
statement is executed. This program displays the following single line of output:


Listing 5.2: Switch2.java—Using the break Statement Within a switch Statement

- 78



class Switch2 {
public static void main(String[] args) {
int n = 3;
switch(n) {
case 1:
System.out.println(1);
break;
case 2:
System.out.println(2);
break;
case 3:
System.out.println(3);
break;
case 4:
System.out.println(4);
break;
case 5:
System.out.println(5);
break;
case 6:
System.out.println(6);
break;
case 7:
System.out.println(7);
break;

default:
System.out.println("default");
}
}
}

- 79



Iteration Statements

Java provides three different types of iteration statements: for, while, and do. These statements,
taken from C and C++, are used to repeat the execution of a statement or block of statements until a
termination condition occurs.

The forStatement

The for statement repeatedly executes a statement or statement block and updates a variable (or
group of variables) with each loop iteration. The syntax of the for statement is


for(initialization; boolean expression; iteration)
statement block
A single statement may be used instead of the statement block. The execution of the for statement is
executed as follows:

1.
The initialization statement(s) are executed to initialize any variables that are used by
the for loop.
2.
The boolean expression is evaluated. If it is true then the statement block is
executed. If it is false, then execution continues after the for statement.
3.
After the statement block is executed, the iteration statement(s) are executed to
increment any loop variables. Execution then continues with Step 2 above.
A typical example of a for statement is

for(int i=0;i// Perform processing using i as an index.
}
The statement block is executed with values of i equal to 0 through n-1. Note that the scope of the
variable i that is declared in the initialization statement is restricted to the for statement and enclosed
statement block.
A little-known fact about the for statement (and one that you may be tested on) is that commas can be
used to separate multiple statements in the initialization and iteration part of the statement. The only
catch is, if you use a comma separator in the initialization block, you cannot declare variables within the
initialization block. For example, the following for statement results in a compilation error:

for(int i=0,int j=0; i+j < 20; ++i, j += i)
{
System.out.println(i+j)
;
}


Listing 5.3 shows a version of the above statement that successfully compiles and produces the
following output:
0
2
5
9
14


Listing 5.3: ForTest.java—An Advanced for Statement


class ForTest {

public static void main(String[] args) {
int i,j;
for(i=0, j=0; i+j < 20; ++i, j += i) {

System.out.println(i+j)
;
}

}


}
The continueStatement

The continue statement is similar to the break statement in that it is used to alter the execution of
for, do, and while statements. Like the break statement, it may be used with or without a label.
When it is used without a label, it causes the statement block of the innermost for, do, or while
statement to terminate and the loop's boolean expression to be reevaluated to determine whether the
next loop repetition should take place. In the case of for statements, the iteration statement(s) are
executed before the loop's boolean expression is reevaluated.
When used with a label, the continue statement transfers control to an enclosing for, do, or while
statement with a matching label. If it is a for statement the iteration statements are executed, and the
loop's boolean expression is reevaluated as a prelude to another loop iteration. If it is a do or while
statement, the loop's boolean expression is reevaluated to determine whether the loop should be
repeated.
Listing 5.4 shows how the continue statement is used with a set of nested for statements. The
output that this program displays is as follows:

i = 1, j =
0
i = 1, j =
1
i = 1, j =
3
i = 2, j =
0
i = 2, j =
2
i = 3, j =
1
i = 4, j =
0
i = 6, j =
0
i = 6, j =
1
i = 6, j =
3
i = 7, j =
0
i = 7, j =
2
i = 8, j =
1
i = 9, j =
0


Listing 5.4: ContinueTest.java—Using a Labeled Continue Statement


class ContinueTest {
public static void main(String[] args) {
outerloop: for(int i=0; i<10; ++i) {
innerloop: for(int j=0; j<10; ++j) {
if((i+j) % 5 == 0) continue outerloop;
if((i+j) % 5 == 3) continue innerloop;
System.out.println("i = "+i+", j = "+j);
}
}
}
}
The while Statement

The while statement, like the for statement, repeatedly executes a statement or statement block.
However, it is not explicitly designed to increment loop variables (although it can) and, as a
consequence, has a much simpler syntax:

while (boolean expression)

statement;

or

while (boolean expression) {

statement(s)

}
The while statement's execution proceeds as follows:


1.
The boolean expression is evaluated. If it evaluates to true, go to step 2. If it
evaluates to false, control passes to the next statement after the while statement.
2. The enclosed statements are executed. Go to step 1.
An example of its use is shown in Listing 5.5. The while statement repeatedly executes until
Math.random() produces a value greater than .5.
Listing 5.5: WhileTest.java—Using the While Statement


class WhileTest {

public static void main(String[] args) {

boolean finished = false;

while (!finished) {

double d = Math.random();

if(d > .5) finished = true;

System.out.println(d);

}

}

}
The do Statement

The do statement is similar to the while statement. The only difference is that the loop condition is
checked after the enclosed statement block is executed (rather than before it). The syntax of the do
statement is

do statement while (loop expression);
or
do
{
statement(s)
} while (loop expression)
;
The do statement's execution proceeds as follows:


1. The enclosed statements are executed. Go to step 2.
2. The boolean expression is evaluated. If it evaluates to true, go to step 1. If it
evaluates to false, control passes to the next statement after the do statement.
Listing 5.5 can be rewritten to use a do statement as follows (see Listing 5.6):

Listing 5.6: DoTest.java—Using the Do Statement


class DoTest {

public static void main(String[] args) {

boolean finished = false;

do {

double d = Math.random();

if(d > .5) finished = true;

System.out.println(d);

} while (!finished);

}

}

Throwing and Catching Exceptions

Java provides superior support for runtime error and exception handling, enabling programs to check for
anomalous conditions and respond to them with minimal impact on the normal flow of program
execution. This allows error- and exception-handling code to be added easily to existing methods.
Exceptions are generated by the Java runtime system in response to errors that are detected as classes
are loaded and their methods are executed. The runtime system is said to throw these runtime
exceptions. Runtime exceptions are objects of the classes java.lang.RuntimeException,
java.lang.Error, or of their subclasses. Runtime exceptions are also referred to as unchecked
exceptions.
Exceptions may also be thrown directly by Java code using the throw statement. These exceptions are
thrown when code detects a condition that could potentially lead to a program malfunction. The
exceptions thrown by user programs are generally not objects of a subclass of RuntimeException.
These non-runtime exceptions are referred to as checked exceptions or program exceptions.

Both program and runtime exceptions must be caught in order for them to be processed by exception-
handling code. If a thrown exception is not caught, its thread of execution is terminated, and an error
message is displayed on the Java console window.
The approach used by Java to catch and handle exceptions is to surround blocks of statements for
which exception processing is performed by a try statement. The try statement contains a catch
clause that identifies what processing is to be performed for different types of exceptions. When an
exception occurs, the Java runtime system matches the exception to the appropriate catch clause. The
catch clause then handles the exception in an appropriate manner. An optional finally clause is
always executed whether or not an exception is thrown or caught. Figure 5.1 summarizes Java's
approach to exception handling.
Figure 5.1: How Java's exception handling works.

The throw Statement

Exceptions are thrown using the throw statement. Its syntax is as follows:

throw Expression;

Note
What to Throw? A throw statement can throw an object of any class that is a
subclass of java.lang.Throwable; however, it is wise to stick with the
standard convention of only throwing objects that are a subclass of class
Exception.

Expression must evaluate to an object that is an instance of a subclass of the
java.lang.Throwable class. When an exception is thrown, execution does not continue after the
throw statement. Instead, it continues with any code that catches the exception. If an exception is not
caught, the current thread of execution is terminated, and an error is displayed on the console window.
Specifically, the uncaughtException() method of the current ThreadGroup is invoked to display
the error message.
For example, the following statement will throw an exception, using an object of class
ExampleException:


throw new ExampleException()
;
The new operator is invoked with the ExampleException() constructor to allocate and initialize an
object of class ExampleException. This object is then thrown by the throw statement.
A method's throws clause lists the types of exceptions that can be thrown during a method's
execution. The throws clause appears immediately before a method's body in the method declaration.
For example, the following method throws the ExampleException:


public void exampleMethod() throws ExampleException
{


throw new ExampleException()
;


}
When more than one exception can be thrown during the execution of a method, the exceptions are
separated by commas in the throws clause. For example, the following method can throw either the
Test1Exception or the Test2Exception:


public void testMethod(int i) throws Test1Exception, Test2Exception
{


if(i==1) throw new Test1Exception()
;


if(i==2) throw new Test2Exception()
;


}


Note
Runtime Exceptions and Errors Because runtime exceptions or errors can
occur almost anywhere in a program's execution, the catch or declare
requirement does not apply to them.

The types identified in the throws clause must be capable of being legally assigned to the exceptions
that may be thrown. In other words, the class of the thrown exception must be castable to the class of
the exceptions identified in the throws clause.
If a program exception can be thrown during the execution of a method, the method must either catch
the exception or declare the exception in its throws clause. This rule applies even if the exception is
thrown in other methods that are invoked during the method's execution.
For example, suppose that method A of object X invokes method Bof object Y, which invokes method C
of object Z. If method C throws an exception, it must be caught by method C or declared in method C's
throws clause. If it is not caught by method C, it must be caught by method B or declared in method B's
throws clause. Similarly, if the exception is not caught by method B, it must be caught by method A or
declared in method A's throws clause. The handling of exceptions is a hierarchical process that mirrors
the method invocation hierarchy (or call tree). Either an exception is caught by a method and removed
from the hierarchy, or it must be declared and propagated back through the method invocation

hierarchy. Figure 5.2 summarizes this process.
Figure 5.2: Declaring or catching exceptions.

The try-catch-finally Statement

Statements for which exception processing is to be performed are surrounded by a try statement with
a valid catch or finally clause (or both). The syntax of the try statement is as follows:


try TryBlock CatchClauses FinallyClause;
At least one catch clause or finally clause must be defined. More than one catch clause may be
used, but no more than one finally clause may be identified.
The try block is a sequence of Java statements that are preceded by an opening brace ({) and
followed by a closing brace (})
.
The catch clauses are a sequence of clauses of the form:


catch (Parameter)
{
/
*


* Exception handling statements
*
/
}
The Parameter is a variable that is declared to be a subclass of Throwable. The statements within
the catch clause are used to process the exceptions that they "catch," as I'll explain shortly.
The finally clause identifies a block of code that is to be executed at the conclusion of the trystatement and after any

catch clauses. Its syntax is as follows:

finally
{
/
*


* Statements in finally clause
*
/
}
The finally clause is always executed, no matter whether or not an exception is thrown.
The try statement executes a statement block. If an exception is thrown during the block's execution, it
terminates execution of the statement block and checks the catch clauses to determine which, if any,
of the catch clauses can catch the thrown exception. If none of the catch clauses can catch the
exception, the exception is propagated to the next level try statement. This process is repeated until
the exception is caught or no more try statements remain. Figure 5.3 summarizes the exception
propagation process.
A catch clause can catch an exception if its argument may be legally assigned the object thrown in the
throw statement. If the argument of a catch clause is a class, the catch clause can catch any object
whose class is a subclass of this class.
The try statement tries each catch clause in order, and selects the first one that can catch the
exception that was thrown. It then executes the statements in the catch clause. If a finally clause
occurs in the try statement, the statements in the finally clause are executed after execution of the
catch clause has been completed. Execution then continues with the statement following the trystatement.
When an exception is caught in the catch clause of a try statement, that exception may be rethrown.
When an exception is rethrown, it can then be caught and processed by the catch clause of a higher-

level try statement. A higher-level catch clause can then perform any secondary clean-up
processing.
Figure 5.3: Exception propagation.
Listing 5.7 provides an example of exception handling. The ExceptionTest program reads a
character entered by the user. It then throws and catches a VowelException, BlankException, or
ExitException based on the user's input.
ExceptionTest provides two static methods, main() and processUserInput(). The main()
method consists of a simple do statement that repeatedly tries to invoke processUserInput(). The
try statement has three catch clauses and a finally clause. The three catch clauses notify the
user of the type of exception they catch. The catch clause with an ExitException parameter causes
the do statement and the program to terminate by setting finished to true. The finally clause just
displays the fact that it has been executed.
The processUserInput() method prompts the user to enter a character. The actual reading of the
character occurs within a try statement. IOException is caught by the try statement, eliminating the
need to declare the exception in the processUserInput()throws clause. The IOException is
handled by notifying the user that the exception occurred and continuing with program execution.
The processUserInput() method throws one of three exceptions based upon the character entered
by the user. If the user enters a vowel, VowelException is thrown. If the user enters a line beginning
with a non-printable character, BlankException is thrown. If the user enters xor X, ExitExceptionis thrown.
When you run ExceptionTest, it produces the following prompt:

Enter a character:

Enter a blank line, and the following output is displayed:
A blank exception occurred.
This is the finally clause.
Enter a character:


The program notifies you that a blank exception has occurred and displays the fact that the finallyclause of the main()try

statement was executed. The processUserInput() method, upon
encountering a space character returned by getChar(), throws the BlankException, which is
caught by the main() method. The finally clause always executes no matter whether
processUserInput() throws an exception or not.
Enter a at the program prompt, and the following output appears:

Enter a character: a


A vowel exception occurred.
This is the finally clause.
Enter a character:


Here the program notifies you that a vowel exception has occurred. The processing of the vowel
exception is similar to the blank exception. See if you can trace the program flow of control involved in
this processing.
Enter j, and the following is displayed:


Enter a character:
j
This is the finally clause.
Enter a character:


No exceptions are thrown for the j character, but the finally clause is executed. The finallyclause is always executed, no

matter what happens during the execution of a try statement. Go ahead
and type x to exit the ExceptionTest program. The program displays the following output:

Enter a character:
x
An exit exception occurred.
This is the finally clause.


The program then returns you to the command prompt. The output acknowledges the fact that the exit
exception was thrown by processUserInput() and caught by main().

Listing 5.7: ExceptionTest.java—Working with Exceptions


import java.io.*;

public class ExceptionTest {

public static void main(String args[]) {
boolean finished = false;
do {

try {
processUserInput();
}catch (VowelException x) {
System.out.println("A vowel exception occurred.");
}catch (BlankException x) {
System.out.println("A blank exception occurred.");

}catch (ExitException x) {
System.out.println("An exit exception occurred.");
finished = true;

}finally {
System.out.println("This is the finally clause.\n");
}
} while(!finished);
}
static void processUserInput() throws VowelException, BlankException,

ExitException
{
System.out.print("Enter a character: ")
;
System.out.flush()
;
char ch;
try
{


BufferedReader kbd =

new BufferedReader(new InputStreamReader(System.in))
;
String line = kbd.readLine()
;
if(line.length() == 0) ch = ' '
;
else ch=Character.toUpperCase(line.charAt(0))
;


} catch (IOException x)
{
System.out.println("An IOException occurred.")
;
return;


}

switch(ch)
{
case 'A'
:
case 'E'
:
case 'I'
:
case 'O'
:
case 'U'
:


throw new VowelException();
case ' ':
throw new BlankException();
case 'X':
throw new ExitException();
}
}
}

class VowelException extends Exception {}

class BlankException extends Exception {}

class ExitException extends Exception {}

Chapter Summary

This chapter covered Java's flow of control and exception handling statements. You learned how to use
the selection statements (if and switch), the iteration statements (for, while, and do), the control
transfer statements (break and continue) and statements used in exception handling (try-catchfinally and throw). You've seen

examples of these statements used in several small programs. You
should now be prepared to test your knowledge of Java statements. The following review questions and
exam questions will let you know how well you understand this material and will give you an idea of how
you'll do in the certification exam questions. They'll also indicate which material you need to study
further.

Key Terms

.
Programming statement
.. Selection statement
.
Iteration statement
.. Exception
.
Throwing an exception
.
Exception handling
Review Questions

1. What is the purpose of a statement block?
2. For which statements does it make sense to use a label?
3. What is the difference between an if statement and a switch statement?
4. What restrictions are placed on the values of each case of a switch statement?
5. How are commas used in the initialization and iteration parts of a for statement?
6. What is the difference between a while statement and a do statement?
7. Can a for statement loop indefinitely?
8. What is the difference between a break statement and a continue statement?
9. What classes of exceptions can be caught by a catch clause?
10. What class of exceptions is generated by the Java run-time system?
11. What happens if an exception is not caught?
12. What is the purpose of the finally clause of a try-catch-finally statement?
13. What classes of exceptions can be thrown by a throw statement?
14. What is the relationship between a method's throws clause and the exceptions that can
be thrown during the method's execution?
15. What is the catch or declare rule for method declarations?
16. What happens if a try-catch-finally statement does not have a catch clause to
handle an exception that is thrown within the body of the try statement?
17. When is the finally clause of a try-catch-finally statement executed?
18. Can an exception be rethrown?
19. Can try statements be nested?
20. How does a try statement determine which catch clause should be used to handle an
exception?
Exam Questions

1. What is wrong with the following if statement?
2. if(x++) {
3. y = x * z;
4. x /= 2;
- 89



5. else {
6. y = y * y;
7. ++z;
}
A. The if condition should use a prefix operator instead of a postfix operator.
B. The if condition must be a boolean expression, not a numeric
expression.
C.
There is a missing } before the else.
D.
There is no break statement to allow control to transfer out of the if
statement.
8.
What is wrong with the following switch statement?
9. switch(i == 10) {
10. case '1':
11. ++i;
12. break;
13. case "2":
14. --i;
15. case 3:
16. i *= 5;
17. break;
18. default
19. i %= 3;
}
A. The switch expression must evaluate to an integer value.
B.
The first case specifies a char value.
C.
The second case specifies a String value.
D.
There is a break statement missing in the second case.
E. An : should follow default.
20. What is wrong with the following for statement?
21. for(i=0; j=0, i<10; ++i, j += i) {
22. k += i*i + j*j;
}
A.
It should include more than one statement in the statement block.
B.
There should be a comma between i=0 and j=0.
C.
It uses more than one loop index.
D.
There should be a semicolon between j=0 and i<10.
23. What is wrong with the following statement?
24. while (x >> 2) do {
25. x *= y;
}
A.
The loop expression is not a boolean expression.
B. The do should be removed.
C. The while should be capitalized.
D.
There is nothing wrong with this statement.
26. What is wrong with the following statements:
27. for(int i=0; i<10; ++i) {
28. if(x[i] > 100) break;
29. if(x[i] < 0) continue;
30. x[i+1] = x[i] + y[i]
;
}
- 90



A.
It is illegal to have a break and continue statement within the same for
statement.
B. The i variable cannot be declared in the initialization part of a for
statement.
C.
The prefix operator is not allowed in the iteration part of a for statement.
D.
There's nothing wrong with the statements.
31. What Java statement is used to completely abort the execution of a loop?
A. The continue statement.
B. The goto statement.
C. The exit statement.
D. The break statement.
32. If you ran the following program, what lines would be included in its output?
33. class Question {
34. public static void main(String[] args) {
35. int i,j;
36. for(i=0, j=0; i+j < 20; ++i, j += i) {
37. System.out.println(i+j);
38. }
39.
}
}
A. 5
B. 8
C. 13
D.
The program cannot be compiled because the for statement's syntax is
incorrect.
40. If you ran the following program, what lines would be included in its output?
41. class Question {
42. public static void main(String[] args) {
43. int i,j;
44. for(i=0, j=0; i+j < 20; ++i, j += i--) {
45. System.out.println(i+j);
46. }
47.
}
}
A. 5
B. 8
C. 13
D.
The program cannot be compiled because the for statement's syntax is
incorrect.
48. If you ran the following program, which lines would be included in its output?
49. class Question {
50. public static void main(String[] args) {
51. int i = 1;
52. int j = 2;
53. outer: while (i < j) {
54. ++i;
55. inner: do {
56. ++j;
- 91



57. if(j % 3 == 0) continue outer;
58. if(i % 3 == 0) break inner;
59. if(i % 3 == 1) break outer;
60. System.out.println(i*j);
61. } while (j < i);
62. System.out.println(i+j);
63. }
64.
}
}
A. 5
B. 6
C. 7
D. The program does not display any output.
65. If you ran the following program, which lines would be included in its output?
66. class Question {
67. public static void main(String[] args) {
68. int i = 1;
69. int j = 2;
70. outer: while (i < j) {
71. ++i;
72. inner: do {
73. ++j;
74. if(i++ % 3 == 2) break inner;
75. else if(j++ % 3 == 1) break outer;
76. System.out.println(i*j);
77. } while (j < i);
78. System.out.println(i+j);
79. }
80.
}
}
A. 5
B. 6
C. 7
D. The program does not display any output.
81. Which of the following must be true of the object thrown by a throw statement?
A. It must be assignable to the Throwable type.
B. It must be assignable to the Error type.
C. It must be assignable to the Exception type.
D. It must be assignable to the String type.
82. A catch clause may catch exceptions of which type?
A. The Throwable type.
B. The Error type.
C. The Exception type.
D. The String type.
83. Which of the following are true about the finally clause of a try-catch-finally
statement?
A. It is only executed after a catch clause has executed.
B. It is only executed if a catch clause has not executed.
- 92



C. It is always executed unless its thread termi-nates.
D. It is only executed if an exception is thrown.
84. Which lines of output are displayed by the following program?
85. class Question {
86. public static void main(String[] args) {
87. for(int i=0;i<10;++i) {
88. try {
89. if(i % 3 == 0) throw new Exception("E0");
90. try {
91. if(i % 3 == 1) throw new Exception("E1");
92. System.out.println(i);
93. }catch (Exception inner) {
94. i *= 2;
95. }finally{
96. ++i;
97. }
98. }catch (Exception outer) {
99. i += 3;
100. }finally{
101. ++i;
102. }
103. }
104.
}
}
A. 4
B. 5
C. 6
D. 7
E. 8
F. 9
105.Which lines of output are displayed by the following program?
106. class Question {
107. public static void main(String[] args) {
108. for(int i=0;i<10;++i) {
109. try {
110. try {
111. if(i % 3 == 0) throw new Exception("E0");
112. System.out.println(i);
113. }catch (Exception inner) {
114. i *= 2;
115. if(i % 3 == 0) throw new Exception("E1");
116. }finally{
117. ++i;
118. }
119. }catch (Exception outer) {
- 93



120. i += 3;
121. }finally{
122. --i;
123. }
124. }
125. }
}

A. 4
B. 5
C. 6
D. 7
E. 8
F.
9
Answers to Review Questions

1.
A statement block is used to organize a sequence of statements as a single statement
group.
2.
The only statements for which it makes sense to use a label are those statements that
can enclose a break or continue statement.
3.
The if statement is used to select among two alternatives. It uses a boolean
expression to decide which alternative should be executed. The switch statement is
used to select among multiple alternatives. It uses an int expression to determine
which alternative should be executed.
4.
During compilation, the values of each case of a switch statement must evaluate to a
value that can be promoted to an int value.
5.
Commas are used to separate multiple statements within the initialization and iteration
parts of a for statement.
6.
A while statement checks at the beginning of a loop to see whether the next loop
iteration should occur. A do statement checks at the end of a loop to see whether the
next iteration of a loop should occur. The do statement will always execute the body of a
loop at least once.
7.
Yes, the for statement can loop indefinitely. For example, consider the statement
for(;;) ;.
8.
A break statement results in the termination of the statement to which it applies
(switch, for, do, or while). A continue statement is used to end the current loop
iteration and return control to the loop statement.
9.
A catch clause can catch any exception that may be assigned to the Throwable type.
This includes the Error and Exception types.
10. The Java runtime system generates RuntimeException and Error exceptions.
11. An uncaught exception results in the uncaughtException() method of the thread's
ThreadGroup being invoked, which eventually results in the termination of the program
in which it is thrown.
12. The finally clause is used to provide the capability to execute code no matter
whether or not an exception is thrown or caught.
13. A throw statement may throw any expression that may be assigned to the Throwable
type.
14. A method's throws clause must declare any checked exceptions that are not caught
within the body of the method.
15. If a checked exception may be thrown within the body of a method, the method must
either catch the exception or declare it in its throws clause.
16. The exception propagates up to the next higher level try-catch statement (if any) or
results in the program's termination.
17. The finally clause of the try-catch-finally statement is always executed unless
the thread of execution terminates or an exception occurs within the execution of the
finally clause.
- 94



18. Yes, an exception can be rethrown.
19. try statements may be nested.
20. When an exception is thrown within the body of a try statement, the catch clauses of
the try statement are examined in the order in which they appear. The first catch
clause that is capable of handling the exception is executed. The remaining catch
clauses are ignored.
Answers to Exam Questions

1.
B and C. The if condition must be a boolean expression. A } is missing from in front
of the else.
2.
A, C, and E. The switch condition must be an integer expression. The case values
must evaluate to integer values during compilation. A : should follow the default label.
3.
B and D. Commas are used to separate statements within the initialization and iteration
parts of a for statement. Semicolons are used to separate the initialization, loop
condition, and iteration parts of the for statement.
4.
A and B. The loop condition must be a boolean expression. There is no do in a while
statement.
5.
D. There's nothing wrong with the statements.
6.
D. The break statement causes a loop's execution to be terminated.
7.
A. The program displays the value 5. It does not display the values 8 or 13.
8.
A, B, and C. The program displays the values 5, 8, and 13.
9.
C. The program displays the value 7.
10. B. The program displays the value 6.
11. A. The object thrown by a throw statement must be assignable to the Throwable type.
This includes the Error and Exception types.
12. A, B, and C. The exception caught by a catch clause must be assignable to the
Throwable type. This includes the Error and Exception types.
13. C .The finally clause of a try-catch statement always executes unless its thread
terminates.
14. B and E. The program only displays the values 5 and 8.
15. A and B. The program only displays the values 4 and 5.

No comments: