0% found this document useful (0 votes)
104 views

04-Flow Control, Exceptions and Assertions PDF

This document discusses flow control, exceptions, and assertions in Java. It provides examples of if/else statements, switch statements, loops (for, while, do-while), breaks, continues, and exceptions. It includes 10 multiple choice questions with explanations about the output or behavior of the code snippets. Overall, the document covers the basic syntax and usage of various flow control structures and exceptions in Java.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
104 views

04-Flow Control, Exceptions and Assertions PDF

This document discusses flow control, exceptions, and assertions in Java. It provides examples of if/else statements, switch statements, loops (for, while, do-while), breaks, continues, and exceptions. It includes 10 multiple choice questions with explanations about the output or behavior of the code snippets. Overall, the document covers the basic syntax and usage of various flow control structures and exceptions in Java.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

CHAPTER 4: FLOW CONTROL, EXCEPTIONS, AND ASSERTIONS

Flow Control (if and switch)

1. Given the following,

1. public class Switch2 {


2. final static short x = 2;
3. public static int y = 0;
4. public static void main(String [] args) {
5. for (int z=0; z < 3; z++) {
6. switch (z) {
7. case y: System.out.print("0 ");
8. case x-1: System.out.print("1 ");
9. case x: System.out.print("2 ");
10. }
11. }
12. }
13. }

What is the result?

A. 0 1 2
B. 0 1 2 1 2 2
C. Compilation fails at line 7.
D. Compilation fails at line 8.
E. Compilation fails at line 9.
F. An exception is thrown at runtime.

ANSWER: C.

Case expressions must be constant expressions. Since x is marked final, lines 8 and 9 are legal;
however, y is not a final so the compiler will fail at line 7.

A, B, D, E, and F, are incorrect based on the program logic described above.

2. Given the following,

1. public class Switch2 {


2. final static short x = 2;
3. public static int y = 0;
4. public static void main(String [] args) {
5. for (int z=0; z < 3; z++) {
6. switch (z) {
7. case x: System.out.print("0 ");
8. case x-1: System.out.print("1 ");
9. case x-2: System.out.print("2 ");
10. }
11. }
12. }
13. }

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College 33


What is the result?

A. 0 1 2
B. 0 1 2 1 2 2
C. 2 1 0 1 0 0
D. 2 1 2 0 1 2
E. Compilation fails at line 8.
F. Compilation fails at line 9.

ANSWER: D

The case expressions are all legal because x is marked final, which means the expressions can
be evaluated at compile time. In the first iteration of the for loop case x-2 matches, so 2 is
printed. In the second iteration, x-1 is matched so 1 and 2 are printed (remember, once a match
is found all remaining statements are executed until a break statement is encountered). In the
third iteration, x is matched so 0 1 and 2 are printed.

A, B, C, E, and F are incorrect based on the program logic described above.

3. Given the following,

1. public class If1 {


2. static boolean b;
3. public static void main(String [] args) {
4. short hand = 42;
5. if ( hand < 50 & !b ) hand++;
6. if ( hand > 50 ) ;
7. else if ( hand > 40 ) {
8. hand += 7;
9. hand++; }
10. else
11. --hand;
12. System.out.println(hand);
13. }
14. }

What is the result?

A. 41
B. 42
C. 50
D. 51
E. Compiler fails at line 5.
F. Compiler fails at line 6.

ANSWER: D

In Java, boolean instance variables are initialized to false, so the if test on line 5 is true and hand
is incremented. Line 6 is legal syntax, a do nothing statement. The else-if is true so hand has 7
added to it and is then incremented.

34 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College


A, B, C, E, and F are incorrect based on the program logic described above.

4. Given the following,

public class Switch2 {


final static short x = 2;
public static int y = 0;

public static void main(String[] args) {


for (int z = 0; z < 4; z++) {
switch (z) {
case x:
System.out.print("0 ");
default:
System.out.print("def ");
case x - 1:
System.out.print("1 ");
break;
case x - 2:
System.out.print("2 ");
}
}
}
}

What is the result?

A. 0 def 1
B. 2 1 0 def 1
C. 2 1 0 def def
D. 2 1 def 0 def 1
E. 2 1 2 0 def 1 2
F. 2 1 0 def 1 def 1

ANSWER: F

When z == 0 , case x-2 is matched. When z == 1, case x-1 is matched and then the break occurs.
When z == 2, case x, then default, then x-1 are all matched. When z == 3, default, then x-1 are
matched. The rules for default are that it will fall through from above like any other case (for
instance when z == 2), and that it will match when no other cases match (for instance when z
== 3).

A, B, C, D, and E are incorrect based on the program logic described above.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College 35


5. Given the following,

public class If2 {


static boolean b1, b2;

public static void main(String[] args) {


int x = 0;
if (!b1) {
if (!b2) {
b1 = true;
x++;
if (5 > 6) {
x++;
}
if (!b1)
x = x + 10;
else if (b2 = true)
x = x + 100;
else if (b1 | b2)
x = x + 1000;
}
}
System.out.println(x);
}
}

What is the result?

A. 0
B. 1
C. 101
D. 111
E. 1001
F. 1101

ANSWER: C

As instance variables, b1 and b2 are initialized to false. The if tests on lines 5 and 6 are
successful so b1 is set to true and x is incremented. The next if test to succeed is on line 13
(note that the code is not testing to see if b2 is true, it is setting b2 to be true). Since line 13 was
successful, subsequent else-if’s (line 14) will be skipped.

A, B, D, E, and F are incorrect based on the program logic described above.

36 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College


Flow Control (loops)

6. Given the following,

1. public class While {


2. public void loop() {
3. int x= 0;
4. while ( 1 ) {
5. System.out.print("x plus one is " + (x + 1));
6. }
7. }
8. }

Which statement is true?

A. There is a syntax error on line 1.


B. There are syntax errors on lines 1 and 4.
C. There are syntax errors on lines 1, 4, and 5.
D. There is a syntax error on line 4.
E. There are syntax errors on lines 4 and 5.
F. There is a syntax error on line 5.

ANSWER: D.

Using the integer 1 in the while statement, or any other looping or conditional construct for that
matter, will result in a compiler error. This is old C syntax, not valid Java.

A, B, C, E, and F are incorrect because line 1 is valid (Java is case sensitive so While is a valid
class name). Line 5 is also valid because an equation may be placed in a String operation as
shown.

7. Given the following,

1. class For {
2. public void test() {
3.
4. System.out.println("x = "+ x);

5. }
6. }
7. }

and the following output,

x=0x=1

Which two lines of code (inserted independently) will cause this output? (Choose two.)

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College 37


A. for (int x = -1; x < 2; ++x) {
B. for (int x = 1; x < 3; ++x ) {
C. for (int x = 0; x > 2; ++x ) {
D. for (int x = 0; x < 2; x++ ) {
E. for (int x = 0; x < 2; ++x ) {

ANSWER: D and E

It doesn’t matter whether you preincrement or postincrement the variable in a for loop; it is
always incremented after the loop executes and before the iteration expression is evaluated.

A and B are incorrect because the first iteration of the loop must be zero. C is incorrect because
the test will fail immediately and the for loop will not be entered.

8. Given the following,

public class Test {


public static void main(String[] args) {
int I = 1;
do
while (I < 1)
System.out.print("I is " + I);
while (I > 1);
}
}

What is the result?

A. I is 1
B. I is 1 I is 1
C. No output is produced.
D. Compilation error
E. I is 1 I is 1 I is 1 in an infinite loop.

ANSWER: C

There are two different looping constructs in this problem. The first is a do-while loop and the
second is a while loop, nested inside the do-while. The body of the do-while is only a single
statement—brackets are not needed. You are assured that the while expression will be
evaluated at least once, followed by an evaluation of the do-while expression. Both expressions
are false and no output is produced.

A, B, D, and E are incorrect based on the program logic described above.

38 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College


9. Given the following,

11. int I = 0;
12. outer:
13. while (true) {
14. I++;
15. inner:
16. for (int j = 0; j < 10; j++) {

17. I += j;
18. if (j == 3)
19. continue inner;
20. break outer;
21. }
22. continue outer;
23. }
24. System.out.println(I);
25.
26.

What is the result?

A. 1
B. 2
C. 3
D. 4

ANSWER: A.

The program flows as follows: I will be incremented after the while loop is entered, then I will
be incremented (by zero) when the for loop is entered. The if statement evaluates to false, and
the continue statement is never reached. The break statement tells the JVM to break out of the
outer loop, at which point I is printed and the fragment is done.

B, C, and D are incorrect based on the program logic described above.

10. Given the following,

1. int I = 0;
2. label:
3. if (I < 2) {
4. System.out.print("I is " + I);
5. I++;
6. continue label;
7. }

What is the result?


A. I is 0
B. I is 0 I is 1
C. Compilation fails.
D. None of the above

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College 39


ANSWER: C

The code will not compile because a continue statement can only occur in a looping construct.
If this syntax were legal, the combination of the continue and the if statements would create a
kludgey kind of loop, but the compiler will force you to write cleaner code than this.

A, B, and D are incorrect based on the program logic described above.

Exceptions

11. Given the following,

1. System.out.print("Start ");
2. try {
3. System.out.print("Hello world");
4. throw new FileNotFoundException();
5. }
6. System.out.print(" Catch Here ");
7. catch(EOFException e) {
8. System.out.print("End of file exception");
9. }
10. catch(FileNotFoundException e) {
11. System.out.print("File not found");
12. }

and given that EOFException and FileNotFoundException are both subclasses of IOException,
and further assuming this block of code is placed into a class, which statement is most true
concerning this code?

A. The code will not compile.


B. Code output: Start Hello world File Not Found.
C. Code output: Start Hello world End of file exception.
D. Code output: Start Hello world Catch Here File not found.

ANSWER: A

Line 6 will cause a compiler error. The only legal statements after try blocks are either catch or
finally statements.

B, C, and D are incorrect based on the program logic described above. If line 6 was removed, the
code would compile and the correct answer would be B.

40 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College


12. Given the following,

public class MyProgram {


public static void main(String args[]) {
try {
System.out.print("Hello world ");
} finally {
System.out.println("Finally executing ");
}
}
}

What is the result?

A. Nothing. The program will not compile because no exceptions are specified.
B. Nothing. The program will not compile because no catch clauses are specified.
C. Hello world.
D. Hello world Finally executing

ANSWER: D

Finally clauses are always executed. The program will first execute the try block, printing Hello
world, and will then execute the finally block, printing Finally executing.

A, B, and C are incorrect based on the program logic described above. Remember that either a
catch or a finally statement must follow a try. Since the finally is present, the catch is not
required.

13. Given the following,

1. import java.io.*;
2. public class MyProgram {
3. public static void main(String args[]){
4. FileOutputStream out = null;

5. try {
6. out = new FileOutputStream("test.txt");
7. out.write(122);
8. }
9. catch(IOException io) {
10. System.out.println("IO Error.");
11. }
12. finally {
13. out.close();
14. }
15. }
16. }

and given that all methods of class FileOutputStream, including close(), throw an
IOException, which of these is true? (Choose one.)

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College 41


A. This program will compile successfully.
B. This program fails to compile due to an error at line 4.
C. This program fails to compile due to an error at line 6.
D. This program fails to compile due to an error at line 9.
E. This program fails to compile due to an error at line 13.

ANSWER: E

Any method (in this case, the main() method) that throws a checked exception (in this case,
out.close() ) must be called within a try clause, or the method must declare that it throws the
exception. Either main() must declare that it throws an exception, or the call to out.close() in
the finally block must fall inside a (in this case nested)
try-catch block.

A, B, C, and D are incorrect based on the program logic described above.

14. Given the following,

public class MyProgram {


public static void throwit() {
throw new RuntimeException();
}

public static void main(String args[]) {


try {
System.out.println("Hello world ");
throwit();
System.out.println("Done with try block ");
} finally {
System.out.println("Finally executing ");
}
}
}

Which answer most closely indicates the behavior of the program?

A. The program will not compile.


B. The program will print Hello world, then will print that a RuntimeException has occurred,
then will print Done with try block, and then will print Finally executing.
C. The program will print Hello world, then will print that a RuntimeException has occurred,
and then will print Finally executing.
D. The program will print Hello world, then will print Finally executing, then will print that a
RuntimeException has occurred.

ANSWER: D

Once the program throws a RuntimeException (in the throwit() method) that is not caught, the
finally block will be executed and the program will be terminated. If a method does not handle
an exception, the finally block is executed before the exception is propagated.

A, B, and C are incorrect based on the program logic described above.

42 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College


15. Given the following,

public class RTExcept {


public static void throwit() {
System.out.print("throwit ");
throw new RuntimeException();
}

public static void main(String[] args) {


try {
System.out.print("hello ");
throwit();
} catch (Exception re) {
System.out.print("caught ");
} finally {
System.out.print("finally ");
}
System.out.println("after ");
}
}

What is the result?

A. hello throwit caught


B. Compilation fails
C. hello throwit RuntimeException caught after
D. hello throwit RuntimeException
E. hello throwit caught finally after
F. hello throwit caught finally after RuntimeException

ANSWER: E

The main() method properly catches and handles the RuntimeException in the catch block,
finally runs (as it always does), and then the code returns to normal.

A, B, C, D, and F are incorrect based on the program logic described above. Remember that
properly handled exceptions do not cause the program to stop executing.

Assertions

16. Which of the following statements is true?

A. In an assert statement, the expression after the colon ( : ) can be any Java expression.
B. If a switch block has no default, adding an assert default is considered appropriate.
C. In an assert statement, if the expression after the colon ( : ) does not have a value, the assert’s
error message will be empty.
D. It is appropriate to handle assertion failures using a catch clause.

ANSWER: B.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College 43


Adding an assertion statement to a switch statement that previously had no default case is
considered an excellent use of the assert mechanism.

A is incorrect because only Java expressions that return a value can be used. For instance, a
method that returns void is illegal. C is incorrect because the expression after the colon must
have a value. D is incorrect because assertions throw errors and not exceptions, and assertion
errors do cause program termination and should not be handled.

17. Which two of the following statements are true? (Choose two.)

A. It is sometimes good practice to throw an AssertionError explicitly.


B. It is good practice to place assertions where you think execution should never reach.
C. Private getter() and setter() methods should not use assertions to verify arguments.
D. If an AssertionError is thrown in a try-catch block, the finally block will be bypassed.
E. It is proper to handle assertion statement failures using a catch (AssertionException ae)
block.

ANSWER: A and B

A is correct because it is sometimes advisable to thrown an assertion error even if assertions


have been disabled. B is correct. One of the most common uses of assert statements in
debugging is to verify that locations in code that have been designed to be unreachable are in
fact never reached.

C is incorrect because it is considered appropriate to check argument values in private methods


using assertions. D is incorrect; finally is never bypassed. E is incorrect because AssertionErrors
should never be handled.

18. Given the following,

public class Test {


public static int y;

public static void foo(int x) {


System.out.print("foo ");
y = x;
}

public static int bar(int z) {


System.out.print("bar ");
return y = z;
}

public static void main(String[] args) {


int t = 0;
assert t > 0 : bar(7);
assert t > 1 : foo(8);
System.out.println("done ");
}
}

44 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College


What is the result?

A. bar
B. bar done
C. foo done
D. bar foo done
E. Compilation fails
F. An error is thrown at runtime.

ANSWER: E

The foo() method returns void. It is a perfectly acceptable method, but because it returns void
it cannot be used in an assert statement, so line 14 will not compile.

A, B, C, D, and F are incorrect based on the program logic described above.

19. Which two of the following statements are true? (Choose two.)

A. If assertions are compiled into a source file, and if no flags are included at runtime, assertions
will execute by default.
B. As of Java version 1.4, assertion statements are compiled by default.
C. With the proper use of runtime arguments, it is possible to instruct the VM to disable
assertions for a certain class, and to enable assertions for a certain package, at the same time.
D. The following are all valid runtime assertion flags:
-ea, -esa, -dsa, -enableassertions,
-disablesystemassertions
E. When evaluating command-line arguments, the VM gives –ea flags precedence over –da
flags.

ANSWER: C and D

C is true because multiple VM flags can be used on a single invocation of a Java program. D is
true, these are all valid flags for the VM.

A is incorrect because at runtime assertions are ignored by default. B is incorrect because as of


Java 1.4 you must add the argument –source 1.4 to the command line if you want the compiler
to compile assertion statements. E is incorrect because the VM evaluates all assertion flags left
to right.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College 45


20. Given the following,

1. public class Test2 {


2. public static int x;
3. public static int foo(int y) {
4. return y * 2;
5. }
6. public static void main(String [] args) {
7. int z = 5;
8. assert z > 0;
9. assert z > 2: foo(z);
10. if ( z < 7 )
11. assert z > 4;
12. switch (z) {
13. case 4: System.out.println("4 ");
14. case 5: System.out.println("5 ");
15. default: assert z < 10;
16. }
17. if ( z < 10 )
18. assert z > 4: z++;
19. System.out.println(z);
20. }
21. }

Which line is an example of an inappropriate use of assertions?

A. Line 8
B. Line 9
C. Line 11
D. Line 15
E. Line 18

ANSWER: E

Assert statements should not cause side effects. Line 18 changes the value of z if the assert
statement is false.

A is fine; a second expression in an assert statement is not required. B is fine because it is


perfectly acceptable to call a method with the second expression of an assert statement. C is
fine because it is proper to call an assert statement conditionally. D is fine because it is
considered good form to add a default assert statement to switch blocks that have no default
case.

46 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College

You might also like