5 - Java OCA 8 - Flow and Control Exceptions

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Given: public class A { public static void main(String[] args) { int[] x = {7,6,5,4,3,2,1}; 4. // insert code here System.out.print(x + " "); } }} Which line, inserted independently at line 4, compiles? (Choose all that apply.) A. for (int y : x) { B. for(x : int y) { C. int y = 0; for (y : x) { D. for (int y=0, z = 0; z<x.length; z++) { y = x[z]; E. for (int y=0, int z = 0; z<x.length; z++) { y = x[z] ; F. int y = 0; for (int z = 0; z<x. length; z++) { y = x[z];

A and F are correct. In the case of answer A: public class A { public static void main(String[] args) { int[] x = {7,6,5,4,3,2,1}; for(int y : x) { System.out.print(y + " "); } }} The above is an enhanced for loop which goes through an array that holds int types starting at index 0 of the array named x. The above is similar to the following syntax: public class A { public static void main(String[] args) { int[] x = {7,6,5,4,3,2,1}; for(int y = 0; y < x.length; y++) { System.out.print(x[y] + " "); } }} Both of the above will output the following: 7 6 5 4 3 2 1 In the case of answer F: The output is also: 7 6 5 4 3 2 1 This answer requires a program step through to be explained more thoroughly. ===Code Step Through=== 1: public class A { 2: public static void main(String[] args) { 3: int[] x = {7,6,5,4,3,2,1}; 4: int y = 0; 5: for (int z = 0; z<x. length; z++) { 6: y = x[z]; 7: System.out.print(y + " "); 8: } }} On the line 3, an array named x containing ints is initialised with values. On the line 4, y is initialized to zero =======2======= 1: public class A { 2: public static void main(String[] args) { 3: int[] x = {7,6,5,4,3,2,1}; 4: int y = 0; 5: for(int z = 0; z<x. length; z++) { 6: y = x[z]; 7: System.out.print(y + " "); 8: } }} On the line 5, starting at the first index of the array, iterate through the array. ======3======= 1: public class A { 2: public static void main(String[] args) { 3: int[] x = {7,6,5,4,3,2,1}; 4: int y = 0; 5: for(int z = 0; z<x. length; z++) { 6: y = x[ z ]; 7: System.out.print(y + " "); 8: } }} On the line 6, get the current int value (x[ z ]), stored within each array index position 'z', and place a copy of it into the variable y. Do this for each of the values within the array x, which are copied to y and then each printed to the screen: 7 6 5 4 3 2 1 ======4======= 1: public class A { 2: public static void main(String[] args) { 3: int[] x = {7,6,5,4,3,2,1}; 4: int y = 0; 5: for (int z = 0; z<x. length; z++) { 6: y = x[z]; 7: System.out.print(y + " "); 8: } }} On the line 7, print the value of y to the screen: 7 6 5 4 3 2 1 Incorrect Answers B will give a compiler error: for(x : int y) { Syntax error which will not compile. ================= C will give a compiler error: int y = 0; for (y : x) { An enhanced for loop cannot have its initiation variable y declared outside of the for block as it gives a compiler error. ================= D will give a compiler error: for (int y=0, z = 0; z<x.length; z++ ) { y = x[z]; The above gives a syntax error as variable z is not declared. Solution: Replace z with y (which was declared in the for loop). ================ E will give a compiler error: for (int y=0, int z = 0; z<x.length; z++ ) { y = x[z]; The above gives a compiler error as this is incorrect syntax to declare an array. It also assigns the value within the array index to the variable y. This is illogical.

public class A { public static void main(String[] args) { // insert code here on line 5 } void go(){ go() ; }} And given the following three code fragments: I. new A().go(); II. try { new A().go(); } catch (Error e) { System.out.println("Caught");} III. try { new A() .go(); } catch (Exception e) { System.out.println("Caught");} When fragments I—III are added, independently, at line 5, which (Choose all that apply.) A. Some will not compile B. They will all compile C. All will complete normally D. None will complete normally E. Only one will complete normally F. Two of them will complete normally

B and E are correct. B. They will all compile. E. Only one will complete normally Summary: I. Runs but the recursive call to the go() method eventually throws an Error (java.lang.StackOverflowError) which is not caught. As a consequence the code does not complete normally. II. Runs runs but the recursive call to the go() method eventually throws an Error (java.lang.StackOverflowError) which is caught. Consequently, "Caught" is printed to the screen. Then the code completes normally. III. Runs but the recursive call to the go() method evenutally throws an Error (StackOverflowError). The Error is not caught therefore the code does not complete normally. Error is not a subclass of Exception. Code I: ===Code Step Through=== 1: public class A { 2: public static void main(String[] args) { 3: new A().go(); 4: } 5: void go(){ 6: go() ; 7: } 8: } On the line 3, a new object instance of class A is created (without a reference) and the go() method gets called using this particular instance of A. =======2======== 1: public class A { 2: public static void main(String[] args) { 3: new A().go(); 4: } 5: void go(){ 6: go(); ⭮ 7: } 8: } On the line 5, the go() method is entered. On the line 6, the go() method is called recursively. A recursive call is where a method is calling itself within the body of its method declaration. Memory Stack-Heap: As stated in Code I above, Local methods and local variables are stored on the Java Stack-Heap. ➤ Local parameters and local variables live near (allocated memory addresses) near the top of the Stack-Heap. ➤ Local methods live near (allocated memory addresses) near the bottom of the Stack-Heap. A never-ending recursive call results in the top of the stack colliding with the bottom of the stack and therefore gives a java.lang.StackOverflowError. Code II: ===Code Step Through=== 1: public class A { 2: public static void main(String[] args) { 3: try { new A().go(); } 4: catch (Error e) { 5: System.out.println("Caught"); 6: } } 7: void go(){ 8: go() ; 9: } 10: } On the line 3, a new object instance of class A is created (without a reference) and the go() method gets called using this particular instance of A. The object instance A and go() method call is wrapped within a try/catch block. =======2======== 1: public class A { 2: public static void main(String[] args) { 3: try { new A().go(); } 4: catch (Error e) { 5: System.out.println("Caught"); 6: } } 5: void go(){ 6: go(); ⭮ 7: } 8: } On the line 5, the go() method is entered. On the line 6, the go()method is called recursively. Memory Stack-Heap: As stated in Code I above, Local methods and local variables are stored on the Java Stack-Heap. ➤ Local parameters and local variables live near (allocated memory addresses) near the top of the Stack-Heap. ➤ Local methods live near (allocated memory addresses) near the bottom of the Stack-Heap. A never-ending recursive call results in the top of the stack colliding with the bottom of the stack and therefore gives a java.lang.StackOverflowError. ========3======= 1: public class A { 2: public static void main(String[] args) { 3: try { new A().go(); } 4: catch (Error e) { 🠄 5: System.out.println("Caught"); 6: } } 5: void go(){ 🠅 6: go(); 7: } 8: } The StackOverflowError that was thrown on the line 7, is caught by the catch on the line 4. The catch block catches Error types. StackOverflowError is a subclass of Error so the catch block is entered and "Caught" is printed to the screen. The program flow control then jumps to the end of the main() method on line 6 and the program completes as normal. Code III: ===Code Step Through=== 1: public class A { 2: public static void main(String[] args) { 3: try { new A().go(); } 4: catch (Exception e) { 5: System.out.println("Caught"); 6: } } 7: void go(){ 8: go(); 9: } 10: } On the line 3, a new object instance of class A is created (without a reference) and the go() method gets called using this particular instance of A. The object instance A and go() method call is wrapped within a try/catch block. ========2======= 1: public class A { 2: public static void main(String[] args) { 3: try { new A().go(); } 4: catch (Exception e) { 5: System.out.println("Caught"); 6: } } 7: void go(){ 8: go(); ⭮ 9: } 10: } On the line 7, the go() method is entered. On the line 8, the go() method is called recursively. Memory Stack-Heap: As stated in Code I above, Local methods and local variables are stored on the Java Stack-Heap. ➤ Local parameters and local variables live near (allocated memory addresses) near the top of the Stack-Heap. ➤ Local methods live near (allocated memory addresses) near the bottom of the Stack-Heap. A never-ending recursive call results in the top of the stack colliding with the bottom of the stack and therefore gives a java.lang.StackOverflowError. =======3======== 1: public class A { 2: public static void main(String[] args) { 🠄 3: try { new A().go(); } 4: catch (Exception e) { 5: System.out.println("Caught"); 6: } } 7: void go(){ 🠅 8: go(); 9: } 10: } On the line 4, is the start of the catch block which catches Exception or subclasses of Exception. However, StackOverflowError is not a type of Exception and is therefore not caught by the catch. This results in the catch block getting skipped a StackOverflowError getting printed to the screen. Therefore this code does not complete normally.

Given that IOException is in the java.io package and given: 1. public class Frisbee { 2. // insert code here 3. int x = 0; 4. System.out.printIn(7/x); 5 } 6 } And given the following four code fragments below: I. public static void main(String[] args) { II. public static void main(String [] args) throws Exception { III. public static void main(String [] args) throws IOException { IV. public static void main(String [] args) throws RuntimeException { If the four fragments are inserted independently at line 2, which are true? (Choose all that apply.) A. All four will compile and execute without exception B. All four will compile and execute and throw an exception C. Some, but not all, will compile and execute without exception D. Some, but not all, will compile and execute and throw an exception

C is correct. Some, but not all, will compile and execute without exception. Dividing a variable by zero will throw an ArithmeticException ===Incorrect Results=== I. public class A { public static void main(String[] args) { int y = 0; System.out.println(7/y); }} The above will compile but when run, will throw a java.lang.ArithmeticException: / by zero. There is no try/catch block to catch the Exception. II. public class A { public static void main(String[] args) throws Exception { int y = 0; System.out.println(7/y); }} The above will also compile but when run will throw a java.lang.ArithmeticException: / by zero III. public class A { public static void main(String[] args) throws IOException { int y = 0; System.out.println(7/y); }} The above will give a compiler error as IOException needs to be explicitly imported. To compile the above you will need to include the following at the start of the code: import java.io.IOException; But will still throw throw a java.lang.ArithmeticException: / by zero when run. IV. public class A { public static void main(String[] args) throws RuntimeException { int y = 0; System.out.println(7/y); }} The above will also compile but when run, it will throw a java.lang.ArithmeticException: / y zero Solution: Wrap the code in a try/catch block. e.g. public class A { public static void main(String[] args){ try { int y = 0; System.out.println(7/y); } catch (Exception e) { System.out.println("Catch"); } }} The above will output "Catch".

Which is correct? (choose all that apply) a) A static initialization block is called only once, no matter how many instances of the class is created b) An initialization block gets called every time the class is constructed c) A static initialization block gets called every time the class is constructed d) An initialization block is called only once, no matter how many instances of the class is created

a) and b) are correct. ➤ a) A static initialization block is called only once, no matter how many instances of the class is created e.g. public class B { static { System.out.print("in static"); } public static void main(String[] args) { B b = new B(); B b2 = new B(); } } Prints: "in static" once even though there were two instantiations of object B. ➤ b) An initialization block gets called every time the class is constructed e.g. public class B { { System.out.print("in static"); } public static void main(String[] args) { B b = new B(); B b2 = new B(); } } The above prints "initialisation block" twice as a consequence of the two instances of class B created i.e. initialisation block initialisation block If there were 50 instances of class B created then there would be 50 outputs of "initialisation block" to the screen. If there were n instances of class B created then there would be n outputs of "initialisation block" to the screen.

Which of the following are correct? (Choose all that apply) a) ArrayIndexOutOfBoundsException is thrown to indicates that array has been accessed with a illegal index . b) ArrayIndexOutOfBoundsException is thrown to indicate that an index of some sort (e.g. array String or Vector) is out of range. c) IndexOutOfBoundsException is thrown to indicate that an index of some sort (e.g. array String or Vector) is out of range. d) none of the above

a) and c) are correct. ➤ IndexOutOfBoundsException is thrown to indicate that an index of some sort (e.g. array String or Vector) is out of range. ➤ ArrayIndexOutOfBoundsException is thrown to indicates that array has been accessed with a illegal index. For example: class A{ public static void main(String[] args) { System.out.print(args[0]); }} > java A The above will throw an ArrayIndexOutOfBoundsException > java A Hi Will print Hi where args[0] is stores "Hi" String

Which of the following will not compile (Choose all that apply) a) for (int i = 0; i < 2; i++) { System.out.print(i); } System.out.print(i); b) for ( int i = 0; i < 2; i++) { System.out.print(i); } for (int i = 0; i < 2; i++) { System.out.print(i); } c) int i=0; for ( i = 0; i < 2; i++) { System.out.print(i); } for ( i = 0; i < 2; i++) { System.out.print(i); } d) none of the above

a) and c) are correct. ➤ a) for (int i = 0; i < 2; i++) { System.out.print(i); } System.out.print( i ); Variable i declared within the for loop and therefore its scope is within the for loop. i attempted to be called after the for loop (outside its scope) therefore compiler error. ➤ c) int i = 0 for ( i = 0; i < 2; i++) { System.out.print(i); } for ( i = 0; i < 2; i++) { System.out.print(i); } You cannot declare the variable outside of a for loop and call it in more than one for loop there after. The Following Will Compile: ➤ b) for (int i = 0; i < 2; i++) { System.out.print(i); } for (int i = 0; i < 2; i++) { System.out.print(i); } The variable i declared within the for loop and therefore its scope is within the for loop. It's okay to have more than one for loop block with the same variable name initializing without a problem because the scope is within particular for loop block

Exception handling in code should be used for: (Choose all that apply) a) Accessing data files b) Performing deep recursion c) Verifying user input d) None of the above

a) and c) are correct. ➤ a) Accessing data files: Data files are usually stored in an external location (e.g. usually on disc). It would be important to ensure that this external data is validated as not being corrupted. Exception handling provides for this to enable the application to still run in the event that data is corrupted. ➤ c) Verifying user input: The user input from the keyboard/mouse (or any other source of input) must be checked to ensure that the mouse click event or keyboard click event is a valid one. Exception handling provides for this to enable the application to still run in the event that an input event is outside the acceptable parameters.

Which of the following exception errors are not subclasses of the Error class? What is the result? (Choose all that apply) a) NoClassDefintionFoundError b) AssertionError c) OutOfMemoryError d) NoClassDefFoundError f) StackOverflowsError

a) and f) are not subclasses of the Error class. a) 'NoClassDefintionFoundError' is a fictitious class that is not located anywhere in the Java API. However, NoClassDefFoundError is a subclass of the Error class which is located in the Java API. f) 'StackOverflowsError' is also a fictitious class that is not located anywhere in the Java API. However, StackOverflowError is a part of the exception class hierarchy which is located in the Java API. This question tests your knowledge of the Exception Class Hierarchy. In particular the Error class and its subclasses. Exception Hierarchy All exception classes (including the Error class and its subclasses) are subtypes of the java.lang.Exception class. It would be imperative to have a core aspect of this Error class hierarchy memorized for the exam. The following is an acronym that may help remember the Error class and its subclasses int the Exception Class Hierarchy: SEANO ➤ StackOverflowError - Method parameters and local variables are allocated arbitrary memory addresses on the stack near the top. Processes/methods are allocated arbitrary memory addresses on the stack near the bottom. A recursive call to a method that never ends results in the top of the stack colliding with the bottom of the heap resulting in a StackOverflowError ➤ ExceptionInInitializerError - This is caused by errors in the static initialization block of code: static int k = 20; static{ k=30/0; }; ➤ AssertionError - This is thrown when a user asserts that the set of arguments passed into parameters are invalid: int i = 0; switch(i){ case 0: System.out.println(); break; case 1: System.out.println(); break; default: new AssertionError(); } ➤ NoClassDefFoundError - This is where the compiler attempts to call a class that does not exist. For example, consider a user attempting to compile a class named 'A' using the command console, but the class 'A' does not exist in the folder named 'code': c:\code>java A This will throw a NoClassDefFoundError. ➤ OutOfMemoryError - This occurs when a memory address cannot be allocated to an object on the heap memory. This is usually caused by external third-party library that holds onto objects that should be sent to garbage collector which results in the stack heap being full. From the acronym 'SEANO', you could quickly sketch the core of the Error subclasses for the exam. Below is a rough outline of the said Error class and it subclasses in the context of the class hierarchy. Let's step through this class hierarchy: Throwable ↑ extends ↑ Error ↑ extends ↑ • StackOverflowError • ExceptionInInitializerError • AssertionError • NoClassDefFoundError • OutOfMemoryError Note: StackOverflowError, ExceptionInInitializerError, AssertionError, NoClassDefFoundError and OutOfMemoryError all extend the Error class on an equal level in the class hierarchy structure.

Given: int j=0; do { if (10%2==0) { break; } //more code// } while (j++>2); What is correct? (Choose all that apply) a) break keyword breaks out of the do while block b) break keyword breaks out of the if block only c) break keyword breaks out of the if block and jumps down to the while condition d) none of the above

a) is correct The 'break' keyword breaks out of the do while block. The break keyword breaks out of the while loop and goes to the next line after the while condition: int j=0; do { if (10%2==0) { break; } //more code// } while (j++>2); //Execute next line after while//

Given: while (true) { LABELA: System.out.println("Label A"); break LABELA; } What is the result? (Choose all that apply) a) compiler error b) runtime error c) compile and print LABELA d) none of the above

a) is correct. The program will give a compiler error while (true) { LABELA: System.out.println("Label A"); break LABELA; } The above will not compile because break is outside of the label: LABELA. Solution: while (true) { LABELA :{ System.out.println("Label A"); break LABELA; } }

Given: public static void main(String[] args) throws Exception { if (args.length == 0) { return; } else{ throw new Exception("Exception"); } System.out.println("End"); } What is the result? (Choose all that apply) a) compiler error b) runtime error c) compile and print "End" d) none of the above

a) is correct. The program will give a compiler error. 1: public static void main(String[] args) throws 2: Exception { 3: if (args.length == 0) { 4: return; 5: } 6: else{ 7: throw new Exception("Exception"); 8: } 9: System.out.println("End"); 10: } On the line 4, 'return' jumps to the end of the main() method to line 10 and skips eveything else. Therefore, line 9 will never be reached and consequently System.out.println("End") is declared as an unreachable statement. The compiler identifies this before runtime

Given: import java.io.IOException; class A { public A() throws Exception{} } import java.io.FileNotFoundException; public class B extends A { public B() throws IOException{} } What is the result? (Choose all that apply) a) compiler error b) runtime error c) compile and run fine d) none of the above

a) is correct. The program will give a compiler error. This question tests your knowledge of constructors that throw exceptions. It is important to be familiar with the Exception Class Hierarchy for this question. Taking an aspect of the exception class hierarchy, we can see that the class Throwable is extended by Exception, which is extended by IOException which is extended by FileNotFoundException: Throwable ↑ extends ↑ Exception ↑ extends ↑ IOException ↑ extends ↑ FileNotFoundException Subclass constructors can only throw the original exception (in this example: IOException) and/or a superclass of the original Exception (in this case Exception and/or Throwable). Let's see how this is implemented in the code: 1: import java.io.IOException; 2: class A { 3: public A() throws Exception{} 4: } 5: import java.io.FileNotFoundException; 6: public class B extends A { 7: public B() throws IOException{} 8: } On the line 3, we can see that the superclass constructor (in class A) can throw an Exception. According to the rules of exception handling, the constructor in the subclass B can only throw: ➤ The original exception (in this case, Exception) and/or ➤ A superclass of the original exception (in this case, Throwable) On line 7, the constructor in class B throws the IOException exception, which will give a compiler error, as it is a subclass of the original exception thrown in class A (i.e. Exception).

Given: int i = 0; switch(i){ System.out.println(0); } What is the result? (Choose all that apply) a) compiler error b) runtime error c) compile and print 0 d) none of the above

a) is correct. The program will give a compiler error. int i = 0; switch(i){ System.out.println(0); } An unlabeled block of code inside a switch block causes a compiler error

Given: public class B extends Exception { static { throw new Exception(); }} What is the result? (Choose all that apply) a) compiler error b) runtime error c) compile and throw an Exception d) none of the above

a) is correct. The program will give a compiler error. public class B extends Exception { static { throw new Exception(); } } When exceptions are thrown in a static initialization block they must be wrapped in a try catch block otherwise it causes a compiler error. Solution: public class B extends Exception { static { try { throw new Exception(); }catch (Exception e) {} } }

Given: try { finally{ System.out.print("Finally"); } } catch (Exception e) { System.out.print("catch"); } What is the result? (Choose all that apply) a) compiler error b) runtime error c) compile and print finally d) none of the above

a) is correct. The program will give a compiler error. try { finally{ System.out.print("Finally"); } } catch (Exception e) { System.out.print("catch"); } The catch block cannot follow the finally block otherwise it will give a compiler error

Given: try { int i = 1; } catch (Exception e) { System.out.println(i); } What is the result? (Choose all that apply) a) compiler error b) runtime error c) compile and print 1 d) none of the above

a) is correct. The program will give a compiler error. try { int i = 1; } catch (Exception e) { System.out.println( i ); } The above will give a compiler error as variable i is declared in the try block so it is not visible in the catch block. When try block completes, all local variables within the try block are destroyed.

Given: public static void main(String[] args) { LABELA: for (int i = 0; i < 2; i++) { System.out.println(i); } break LABELA; } What is the result? (Choose all that apply) a) compiler error b) runtime error c) compile and print 0 1 d) none of the above

a) is correct. The program will give a compiler error. public static void main(String[] args) { LABELA: for(int i = 0; i < 2; i++) { System.out.println(i); } break LABELA; } The 'break LABELA' is out of the loop therefore compiler error. Solution: public static void main(String[] args) { LABELA: for(int i = 0; i < 2; i++) { System.out.println(i); break LABELA; } }

Given: int i = 0; switch(i){ boolean f = true; } What is the result? (Choose all that apply) a) compiler error b) runtime error c) compile and run fine d) none of the above

a) is correct. The program will give a compiler error. You cannot have an unlabeled block of code inside the switch block int i = 0; switch(i){ boolean f = true; } In the above code sample, 'boolean f = true' is an unlabeled block of code inside a switch block which gives a compiler error.

Given: int y=0; do { System.out.print(y); y++; } while (y<2) What is the result? (Choose all that apply) a) compiler error b) runtime error c) compile and print 01 d) none of the above

a) is correct. The program will will give a compiler error. Syntax error missing ' ; ' at the end of the while condition: int y=0; do { System.out.print(y); y++; } while (y<2) ;

Given: public static void main(String[] args) { System.out.println(Integer.parseInt("12.3")); } What is the result? (Choose all that apply) a) compiler error b) runtime error c) compile and print 12 d) compile and print 12.3

b) is correct. The program will throw a runtime error. public static void main(String[] args) { System.out.println(Integer.parseInt("12.3")); } The above code will give a: java.lang.NumberFormatException: For input string: "12.3". This is because the method parseInt() only takes Integers.

Which of the following is the same as 'while(true){}'? (Choose all that apply) a) for( ; ) b) for( ; ; ) c) for(true) d) none of the above

b) is correct. for( ; ; )

Given: import java.io.IOException; class A { void m() throws IOException{} } public class B extends A { public void m() throws Exception{ System.out.println("B"); }} What is the result? (Choose all that apply) a) compiler error b) runtime error c) compile and run fine d) none of the above

a) is correct. The program will give a compiler error. This question tests your knowledge of methods that throw exceptions. It is important to be familiar with the Exception Class Hierarchy for this question. Taking an aspect of the exception class hierarchybelow, we can see that the class Throwable is extended by Exception, which is extended by IOException which is extended by FileNotFoundException: Throwable ↑ extends ↑ Exception ↑ extends ↑ IOException ↑ extends ↑ FileNotFoundException Overriding methods can only throw the original exception (in this example: IOException) and/or subclass of the original Exception (in this case FileNotFoundException). Let's examine the code: 1: import java.io.IOException; 2: class A { 3: void m() throws IOException{} 4: } 5: public class B extends A { 6: public void m() throws Exception{ 7: System.out.println("B"); 8: }} On the line 3, we can see that the superclass class A method m() can throw an IOException. According to the rules of exception handling, the overriding method m() in the subclass B can only throw: ➤ The original exception (in this case, IOException) and/or ➤ A subclass of the original exception (in this case, FileNotFoundException) On line 6, the overriding method m(), in class B, throws the Exception. As Exception is a superclass of the original exception thrown in class A, a compiler error occurs. Note: If the subclass method m() threw FileNotFoundException and/or Exception, it would compile and run fine.

Exception handling is used for which the following? (Choose all that apply) a) Catch division by zero. b) Thread Interruption. c) Mouse clicks d) Invalid Parameters e) Disk I/O.

a), b) and d) are correct. The following is a suggested abbreviation to help memorise the reasons for exception handling: DIT-AO ➤ Division by zero ➤ Invalid parameters ➤ Thread interruption ➤ Arithmetic overflow ➤ Out of range array indexes. Exception handling is not used for asynchronous events like: • Mouse clicks. • Disk I/O • Network Message Arrivals.

Which of the following are exceptions typically thrown by the developer? (Choose all that apply) a) AssertionError b) IndexOutOfBoundsException c) IllegalArgumentsException d) NumberFormatException

a), c) and d) are correct. Below you'll find the list of exceptions typically thrown by the developer. The following is a suggested abbreviation to help memorise for this particular question: AINI ➤ AssertionError - asserts that the state of the system is true at a certain point in time otherwise throw an assertion error ➤ IllegalArgumentsException - when arguments passed to a method are incorrect or incorrect parameters ➤ NumberFormatException - when the method is meant to convert a String to a number receives an illegal format of a String ➤ IllegalStateException - when a method is called at an illegal time The following are exceptions typically trolled by the compiler: ➤ IndexOutOfBoundsException is thrown to indicate that an index of some sort (e.g. array String or Vector) is out of range ➤ ArrayIndexOutOfBoundsException is thrown to indicates that array has been accessed with a illegal index. For example: class A{ public static void main(String[] args) { System.out.print(args[0]); }} > java A The above will throw an ArrayIndexOutOfBoundsException > java A Hi Will print Hi where args[0] is stores "Hi" String

Which of the following are false? (Choose all that apply) a) Java is multithreaded so if the program has multiple threads - uncaught exceptions will terminate only in the thread with the exception occurred b) Java is multithreaded so if the program has multiple threads - uncaught exceptions will terminate only in the all threads where the exception occurred c) After the exception is handled and the try block expired-local variables are lost in the try block d) After the exception is handled and the try block expired - local variables in the try block are kept

b) and d) are correct. ➤ Java is multithreaded, so if the program has multiple threads, uncaught exceptions will terminate only in the thread where the exception occurred ➤ After the exception is handled and the try block expired, local variables are lost in the try block

Which of the following will not compile? (Choose all that apply) a) for (String s : args) { s = new String(); } b) for (final String s : args) { s = new String(); } c) int j = 0; for ( j = 0; j < 10; j++) { } d) int j = 0; for ( j; j < 10; j++) { }

b) and d) will not compile. ➤ b) for (final String s : args) { s = new String(); } s is final and cannot be changed - compiler error ➤ d) int j = 0; for ( j ; j < 10; j++) { } A predefined variable will give a compiler error The Following Will Compile c) int j = 0; for ( j = 0; j < 10; j++) { } Declaring a variable j before the loop and reinitializing inside the loop is okay Note: The following will give a compiler error: int j ; for ( j = 0; j < 10; j++) { } Note: You cannot use a predefined variable in varibale declaration of an enhanced for loop- compiler error e.g. String s = "hello"; for (s : args) { }

Which of the following will not compile? (Choose all that apply) a) switch(5){ default: } b) switch(5); c) int x=8; switch(x){ default: } d) switch(5){ default: break; }

b) is correct switch(5); The above will give a compiler error. A switch statement must have a body and it can be empty e.g. switch(5) { }

Which of the following are incorrect? (Choose all that apply) Checked Exceptions: a) Are thrown by errors in inside code b) Are thrown by errors in outside code c) Caused by the Throwable class and all user-defined subclasses of Throwable d) IOException and all its subclasses

b) is incorrect. Checked Exceptions: a) Are thrown by errors inside the code c) Caused by the Throwable class and all user-defined subclasses of Throwable d) IOException and all its subclasses. ➤ Exception class and all user-defined subclasses of Throwable must explicitly specify in a try catch block or throws clause

Given: class A{ static String s = "-"; public static void main(String[] args) { new A().si(); System.out.println(s); } void si() { try { s2(); } catch (Exception e) { s += "c"; } } void s2() throws Exception { s3(); s += "2"; s3(); s += "2b"; } void s3() throws Exception { throw new Exception(); } } What is the result? A. - B. -c C. -c2 D. -2c E. -c22b F. -2c2b G. -2c2bc H. Compilation fails

b) is correct. The output is: "-c" ===Code Step Through=== 1: class A{ 2: static String s = "-"; 3: public static void main(String[] args) { 4: new A().si(); 5: System.out.println(s); 6: } 7: void si() { 8: try { s2(); } 9: catch (Exception e) { s += "c"; } 10: } 11: void s2() throws Exception { 12: s3(); 13: s += "2"; 14: s3(); 15: s += "2b"; 16: } 17: void s3() throws Exception { 18: throw new Exception(); 19: } 20: } On the line 4, a new object instance of class A is created. The static string s is then initialized with "-". Current value stored in memory: s = "-" ==========2=========== 1: class A{ 2: static String s = "-"; 3: public static void main(String[] args) { 4: new A().si(); 5: System.out.println(s); 6: } 7: void si(){ 8: try { s2(); } 9: catch (Exception e) { s += "c"; } 10: } 11: void s2() throws Exception { 12: s3(); 13: s += "2"; 14: s3(); 15: s += "2b"; 16: } 17: void s3() throws Exception { 18: throw new Exception(); 19: } 20: } On the line 4, the method si() is called. Program flow then jumps to line 7 and enters the said method body of si(). =======3====== 1: class A{ 2: static String s = "-"; 3: public static void main(String[] args) { 4: new A().si(); 5: System.out.println(s); 6: } 7: void si(){ 8: try { s2(); } 9: catch (Exception e) { s += "c"; } 10: } 11: void s2() throws Exception { 12: s3(); 13: s += "2"; 14: s3(); 15: s += "2b"; 16: } 17: void s3() throws Exception { 18: throw new Exception(); 19: } 20: } On the line 8, inside si() body, s2() is called. Program flow then jumps to line 11 and enters the said method s2(). ======4====== 1: class A{ 2: static String s = "-"; 3: public static void main(String[] args) { 4: new A().si(); 5: System.out.println(s); 6: } 7: void si(){ 8: try { s2(); } 9: catch (Exception e) { s += "c"; } 10: } 11: void s2() throws Exception { 12: s3(); 13: s += "2"; 14: s3(); 15: s += "2b"; 16: } 17: void s3() throws Exception { 18: throw new Exception(); 19: } 20: } On the line 12, the method s3() gets called. Program flow then jumps to line 17 and enters the method s3(). ======5===== 1: class A{ 2: static String s = "-"; 3: public static void main(String[] args) { 4: new A().si(); 5: System.out.println(s); 6: } 7: void si(){ 🠄 8: try { s2(); } 9: catch (Exception e) { s += "c"; } 10: } 11: void s2() throws Exception { 🠅 12: s3(); 13: s += "2"; 14: s3(); 15: s += "2b"; 16: } 17: void s3() throws Exception { 18: throw new Exception(); 🠅 19: } 20: } On the line 18, the method s3() throws an Exception object (checked exception). The JVM then seeks to find who is responsible for catching the exception thrown on line 18. There is no catch block in the method s3(), so program flow jumps back into method s2(). Inside s2(), there is no catch block to catch the said exception in s2() so the program flow jumps back up into method si() on line 7. Inside method si(), on the line 9, the exception (thrown on line 18) is caught. =====6===== 1: class A{ 2: static String s = "-"; 3: public static void main(String[] args) { 4: new A().si(); 5: System.out.println(s); 6: } 7: void si(){ 8: try { s2(); } 9: catch (Exception e) { s += "c"; } 🠄 10: } 11: void s2() throws Exception { 12: s3(); 13: s += "2"; 14: s3(); 15: s += "2b"; 16: } 17: void s3() throws Exception { 18: throw new Exception(); 19: } 20: } As stated above, the thrown Exception on the line 18, is caught inside the method si() and program flow enters the catch block of the method si(), on the line 9. As a consequence of the thrown exception (on the line 18 inside the method s3()), the rest of the instructions inside the method s2(), on the lines 13, 14, and 15 are skipped. The above part of the code is the most important aspect to understand in this code step through. =====7===== 1: class A{ 2: static String s = "-"; 3: public static void main(String[] args) { 4: new A().si(); 5: System.out.println(s); 6: } 7: void si(){ 8: try { s2(); } 9: catch (Exception e) { s += "c"; } 🠄 10: } 11: void s2() throws Exception { 12: s3(); 13: s += "2"; 14: s3(); 15: s += "2b"; 16: } 17: void s3() throws Exception { 18: throw new Exception(); 19: } 20: } Inside the si() catch block, on the line 9, "c" is appened to string s resulting "-c" stored in the string s. Current value stored in memory: s = "-c" =========8============ 1: class A{ 2: static String s = "-"; 3: public static void main(String[] args){ 4: new A().si(); 5: System.out.println(s); 🠄 6: } 7: void si(){ 8: try { s2(); } 9: catch (Exception e) { s += "c"; } 10: } 🠅 11: void s2() throws Exception { 12: s3(); 13: s += "2"; 14: s3(); 15: s += "2b"; 16: } 17: void s3() throws Exception { 18: throw new Exception(); 19: } 20: } After the catch block on the line 9 is completed, the program flow jumps to the end of the method si() and returns to the main() method on the line 5 and the string 's' gets printed to the screen: "-c" Note: When an object of a class is created, static initialization blocks get initialized first, followed by static methods, followed by non-static initialization blocks, followed by member (instance) variables and member methods.

Given: public class A { public static void main(String [] args) { String o ="-"; String [] sa = new String[3]; for(int i = 0; i < args.length; i++ ) sa [i] = args [i] ; for(String n: sa) { switch(n.toLowerCase()) { case "yellow": o += "y"; case "red": o += "r"; case "green": o += "g"; } } System.out.print(o); } } Given the command line invocation: java A RED Green yeLLow What is the result? (Choose all that apply) a) compiler error b) runtime error c) compile and print -rggyrg d) none of the above

b) is correct. The program throws an ArrayIndexOutOfBoundsException ===Code Step Through=== 1: public class A { 2: public static void main(String [] args) { 3: String o ="-"; 4: String [] sa = new String[3]; 5: for(int i = 0; i < args.length; i++ ) 6: sa [i] = args [i] ; 7: for(String n: sa) { 8: switch(n.toLowerCase()) { 9: case "yellow": o += "y"; 10: case "red": o += "r"; 11: case "green": o += "g"; 12: } 13: } 14: System.out.print(o); 15: } 16: } On the line 3, the string 'o' is assigned the value '-'. On the line 4, an object array of type String is created which can hold a maximum of 3 objects. When initialised, the contents of string array objects all get a default value of 'null': sa[0] = null sa[1] = null sa[2] = null ========2======== 1: public class A { 2: public static void main(String [] args) { 3: String o ="-"; 4: String [] sa = new String[3]; 5: for(int i = 0; i < args.length; i++ ) 6: sa [i] = args [i]; 7: for(String n: sa) { 8: switch(n.toLowerCase()) { 9: case "yellow": o += "y"; 10: case "red": o += "r"; 11: case "green": o += "g"; 12: } 13: } 14: System.out.print(o); 15: } 16: } On the line 5, the variable ' i ' gets initialized to 0 and the for block is entered. As there is no brackets '{}' in the for block, there is only one line to execute inside the for block on line 6. Current value stored in memory: sa[0] = null sa[1] = null sa[2] = null i = 0 =========3============ 1: public class A { 2: public static void main(String [] args) { 3: String o ="-"; 4: String [] sa = new String[3]; 5: for(int i = 0; i < args.length; i++ ) 6: sa[ i ] = args[ i ]; 7: for(String n: sa) { 8: switch(n.toLowerCase()) { 9: case "yellow": o += "y"; 10: case "red": o += "r"; 11: case "green": o += "g"; 12: } 13: } 14: System.out.print(o); 15: } 16: } The following is inputted into the command line: >java A RED Green yeLLow pink The input string RED Green yeLLow pink is attempted to be stored in the args[ ] array as follows: args[ 0 ]= RED; args[ 1 ]= Green; args[ 2 ]= yeLLow; args[ 3 ]= pink; The args[ ] array is of size 4 with indexes 0 to 3. On the line 4, the String array is declared of size 3: String [] sa = new String[3]; On the line 6, the exception occurs when an attempt is made to copy the contents of the args array into the array sa. As the args[ ] array is of size 4 and the array sa[] is of size 3, this is where the problem occurs. Attempting to copy the last value "pink" into sa[ ] will give an ArrayIndexOutOfBoundsException as there is not an sa[ 3 ].

Given: for (int j = 0; j < 2; j++) { switch(j++){ case 0: System.out.println("A"); break; case 1: System.out.println("B"); break; }} What is the result? (Choose all that apply) a) compiler error b) compile and print A c) compile and print A B d) none of the above

b) is correct. The program will compile and print: A This question tests your knowledge of 'for' loops and switch blocks. ===Code Step Through=== 1: for (int j = 0; j < 2; j++) { 2: switch(j++){ 3: case 0: System.out.println("A"); 4: break; 5: case 1: System.out.println("B"); 6: break; 7: } } On the line 1, the variable j is initialised to 0 and the 'for block' is entered. =======2======= 1: for (int j = 0; j < 2; j++) { 2: switch(j++){ 3: case 0: System.out.println("A"); 4: break; 5: case 1: System.out.println("B"); 6: break; 7: } } The variable ' j ' has a postfix operator (j++). This means that the varable j is incremented by 1 AFTER the switch block iteration completes. Therefore, the current value stored in variable j is 0. ============== Snapshot of Variables in Memory: j = 0 =======3======= 1: for (int j = 0; j < 2; j++) { 2: switch(j++){ 3: case 0: System.out.println("A"); 4: break; 5: case 1: System.out.println("B"); 6: break; 7: } } The current value stored in variable j is 0. This is matched by the case 0 in the switch block on the line 3. Therefore, "A" gets printed to the screen. ========4======= 1: for (int j = 0; j < 2; j++) { 2: switch(j++){ 3: case 0: System.out.println("A"); 4: break; 5: case 1: System.out.println("B"); 6: break; 7: } } On the line 4, the 'break' keyword is executed which so the program jumps to the end of switch block, to line 7. On the line 7, the postfix operator of the variable j (on line 2) is executed. This increments the variable ' j ', to the value 1. ============== Snapshot of Variables in Memory: j = 1 =======5======= 1: for (int j = 0; j < 2; j++) { 2: switch(j++){ 3: case 0: System.out.println("A"); 4: break; 5: case 1: System.out.println("B"); 6: break; 7: } } On the line 7, at the end of the for loop, the postfix operator of the variable j (on line 1) is executed. This increments the variable ' j , again to the value 2. ============== Snapshot of Variables in Memory: j = 2 =======6======= 1: for (int j = 0; j < 2; j++) { 2: switch(j++){ 3: case 0: System.out.println("A"); 4: break; 5: case 1: System.out.println("B"); 6: break; 7: } } The for loop iterates for the second occasion and compares the content of the current variable j see if it is less than the value 2. As this is false, the for loop is skipped. The programme ceases.

Given: 1: class MyException1 extends Exception {} 2: class MyException2 extends MyException1 {} 3: public class A { 4: void m() throws MyException1{} 5: } 6: class B extends A { 7: void m() throws MyException2{} 8: } 9: class C extends A { 10: void m() throws Exception{} 11:} What is the result? (Choose all that apply) a) Compiler error on line 7 b) Compiler error on line 10 c) Compiler error on line 4 d) Compiles and runs fine e) none of the above

b) is correct. The program will give a compiler error on line 10. When undertaking these questions, which incorporate a Exception Class Hierarchy structure, it would be beneficial to sketch out the class hierarchy of the code. In terms of the Exception class hierarchy aspect of the code, we can see that MyException1 and MyException2 extend the Exception class: Throwable ↑ extends ↑ Exception ↑ extends ↑ MyException1 ↑ extends ↑ MyException2 A developer can create their own exceptions by extending the Exception class as outlined in this code sample with MyException1 and MyException2. In the context of when methods throw exceptions, an overriding method cannot throw a broader (super class) exception than the method it's overriding. In referencing the class hierarchy diagram sketch above, you can see that MyException1 is a subtype of Exception (as MyException1 extends Exception). The code sample below highlights on line 10, that method m() in class C throws a broader exception (Exception) of the the method it's overriding, method m() in class A (MyException1) on line 4. This gives a compiler error: 1: class MyException1 extends Exception{} 2: class MyException2 extends MyException1{} 3: public class A { 4: void m() throws MyException1{} 5: } 6: class B extends A { 7: void m() throws MyException2 {} 8: } 9: class C extends A { 10: void m() throws Exception{} 11:} Solution: Have the overriding method throw the same exception as the superclass or a subclass of the superclass exception. In the below program sample, you can see that the method overriding m() in class C throws the same exception as method m() in class A (i.e. MyException1). 1: class MyException1 extends Exception{} 2: class MyException2 extends MyException1{} 3: public class A { 4: void m() throws MyException1{} 5: } 6: class B extends A { 7: void m() throws MyException2 {} 8: } 9: class C extends A { 10: void m() throws MyException1{} 11:} You could also have m() in class C throw MyException2 (like m() in class B) as it is a subclass of the original exception thrown by m() in class A.

Given:: class A { static void throwIt(){ throw new RuntimeException(); } public static void main(String[] args){ try { throwIt(); System.out.println("In Try"); } finally{ System.out.println("In finally"); }} } What is the result? (Choose all that apply) a) compiler error b) runtime error c) compile and print In Try In finally d) none of the above

b) is correct. The program will give a runtime error. ===Code Step Through=== 1: class A { 2: static void throwIt(){ 3: throw new RuntimeException(); 4: } 5: public static void main(String[] args){ 6: try { 7: throwIt(); 8: System.out.println("In Try"); 9: } 10: finally{ 11: System.out.println("In finally"); 12: }} } On the line 7, in the main method, throwIt() gets called in try block. =======2======= 1: class A { 2: static void throwIt(){ 3: throw new RuntimeException(); 4: } 5: public static void main(String[] args){ 6: try { 7: throwIt(); 8: System.out.println("In Try"); 9: } 10: finally{ 11: System.out.println("In finally"); 12: }} } On the line 2, the throwIt() method is entered. On the line 3, a RuntimeException (unchecked exception) is thrown. =======3======= 1: class A { 2: static void throwIt(){ 3: throw new RuntimeException(); 4: } 5: public static void main(String[] args){ 6: try { 7: throwIt(); 8: System.out.println("In Try"); 9: } 10: finally{ 11: System.out.println("In finally"); 12: } } } Following the execution of the line 7, the program flow skips the rest of the try block (i.e. line 8 containing the statement System.out.println("In Try")). The program flow then jumps into the finally block and prints "In finally". The finally block of code will be executed even if an exception is explicitly thrown, as was the case the line 3. =======4======= 1: class A { 2: static void throwIt(){ 3: throw new RuntimeException(); 4: } 5: public static void main(String[] args){ 6: try { 7: throwIt(); 8: System.out.println("In Try"); 9: } 10: finally{ 11: System.out.println("In finally"); 12: } } } Execution exits the finally block and then throws RuntimeException at the end of the main() method on the line 12.

Exception handling is NOT used for which the following? (Choose all that apply) a) Catch division by zero. b) Thread Interruption. c) Mouse clicks d) Invalid Parameters e) Disk I/O.

c) and d) are correct. Exception handling is not used for asynchronous events. The following is a suggested abbreviation to help memorise three examples of asynchronous events: MDN ➤ Mouse clicks ➤ Disc I/O ➤ Network message arrivals.

Given: try { int x = Integer.parseInt("two"); } Which could be used to create an appropriate catch block? Choose all that apply. The above code will give: a) ClassCastException b) IlegalStateException c) NumberFormatException d) IlegalArgumentException e) ExceptionInInitialiserError f) ArrayIndexOutOfBoundsException

c) and d) are correct. The following exceptions could be used to create an appropriate catch block: c) NumberFormatException d) IlegalArgumentException Let's look at what we are trying to catch: int x = Integer.parseInt("two"); The above gives a compiler error as parseInt() takes an String when it should only take digits As a consequence, it gives a NumberFormatException. Looking at the class hierarchy below we can see that Exception is a superclass of RuntimeException which is a superclass of IlegalArgumentException which is a superclass of NumberFormatException: Throwable -----↑------ --extends-- -----↑------ Exception -----↑------ --extends-- -----↑------ RuntimeException -----↑------ --extends-- -----↑------ IlegalArgumentException -----↑------ --extends-- -----↑------ NumberFormatException The superclass of NumberFormatException can also be used i.e. IlegalArgumentException Note: All of the below would not the able to catch the said exception (parseInt("two")): a) ClassCastException b) IlegalStateException e) ExceptionInInitialiserError f) ArrayIndexOutOfBoundsException As a tip for the exam, it would be advisable to quickly write out the Exception Hierarchy. Exception Hierarchy All exception classes are subtypes of the java.lang.Exception class. The Exception class is a subclass of the Throwable class. It would be imperative to have a core aspect of this exception class hierarchy memorized for the exam. Exception Hierarchy All exception classes are subtypes of the java.lang.Exception class. The Exception class is a subclass of the Throwable class. It would be imperative to have a core aspect of this exception class hierarchy memorized for the exam. The following is an acronym to help remember the Exception Class Hierarchy: TEERIIII-CAN ➤ Throwable (checked exception) - must be wrapped in a try catch block or throws clause ➤ Exception (checked exception) extends Throwable - must be wrapped in a try catch block or throws clause ➤ Error (unchecked exception) extends Throwable - thrown by Java virtual machine JVM ➤ RuntimeException (unchecked exception) extends Exception - thrown by Java virtual machine JVM ➤ IllegalArgumentsException (unchecked exception) extends RuntimeException - thrown by JVM e.g. parameter passed to methods not valid ➤ IndexOutOfBoundsException (unchecked exception) extends RuntimeException - thrown by JVM e.g. Array String Vector ➤ IllegalStateException (unchecked exception) extends RuntimeException - thrown by JVM e.g. a method called at an illegal time ➤ IOException (checked exception) extends Exception - must be wrapped in a try catch block or throws clause ➤ ClassCastException (unchecked exception) extends RuntimeException - thrown by JVM e.g. Object x = new Integer(0); (String) x ➤ ArithmeticException (unchecked exception) extends RuntimeException - thrown by JVM e.g. 1/0 ➤ NullPointerException (unchecked exception) extends RuntimeException - thrown by JVM e.g. String s; s.isEmpty(); From the above, you could quickly sketch the core of the Exception Class Hierarchy for the exam.

Which of the following are not in the Exception Class Hierarchy? (Choose all that apply) a) IllegalArgumentsException b) NullPointerException c) CastException d) Throwable e) ArgumentsException

c) and e) are not in the exception class hierarchy. ➤ CastException is a fictitious class that is not located anywhere in the Java API. However, ClassCastException is a part of the exception class hierarchy. ➤ ArgumentsException is also a fictitious class that is not located anywhere in the Java API. However, IllegalArgumentsException is a part of the exception class hierarchy. This question tests your knowledge of the Exception Class Hierarchy. Exception Hierarchy All exception classes are subtypes of the java.lang.Exception class. The Exception class is a subclass of the Throwable class. It would be imperative to have a core aspect of this exception class hierarchy memorized for the exam. The following is an acronym to help remember the Exception Class Hierarchy: TEERIIII-CAN ➤ Throwable (checked exception) - must be wrapped in a try catch block or throws clause ➤ Exception (checked exception) extends Throwable - must be wrapped in a try catch block or throws clause ➤ Error (unchecked exception) extends Throwable - thrown by Java virtual machine JVM ➤ RuntimeException (unchecked exception) extends Exception - thrown by Java virtual machine JVM ➤ IllegalArgumentsException (unchecked exception) extends RuntimeException - thrown by JVM e.g. parameter passed to methods not valid ➤ IndexOutOfBoundsException (unchecked exception) extends RuntimeException - thrown by JVM e.g. Array String Vector ➤ IllegalStateException (unchecked exception) extends RuntimeException - thrown by JVM e.g. a method called at an illegal time ➤ IOException (checked exception) extends Exception - must be wrapped in a try catch block or throws clause ➤ ClassCastException (unchecked exception) extends RuntimeException - thrown by JVM e.g. Object x = new Integer(0); (String) x ➤ ArithmeticException (unchecked exception) extends RuntimeException - thrown by JVM e.g. 1/0 ➤ NullPointerException (unchecked exception) extends RuntimeException - thrown by JVM e.g. String s; s.isEmpty(); From the above, you could quickly sketch the core of the Exception Class Hierarchy for the exam.

Given: int i = 1; switch(i){ default: System.out.println("default"); case 1: System.out.println("1"); case 0: System.out.println("0"); break; } What is the result? a) compiler error b) compile and print 1 c) compile and print 1 0 d) compile and print default 1 0

c) is correct The program compiles and prints: 1 0 int i = 1; switch( i ){ default: System.out.println("default"); case 1: System.out.println("1"); case 0: System.out.println("0"); break; } No break between case 1 and 0 therefore it falls through.

Given: for (int i = 0, j=0; i < 2; i++, j++) { System.out.println(i+" "+j); } What is the result? (Choose all that apply) a) compiler error b) compile and print: 0 0 c) compile and print: 0 0 1 1 d) none of the above

c) is correct The program will compile and print: 0 0 1 1 Let's step through the code below: ===Code Step Through=== for (int i = 0, j =0; i < 2; i++, j++) { System.out.println(i+" "+j); } The variables i and j get initialized with value 0. Current Memory Snapshot i =0 j =0 ========2======== for (int i = 0, j=0; i < 2; i++, j++) { System.out.println(i+" "+j); } Check if the current value stored in variable i (i.e. 0) is less than the value 2. Answer: True ========3======== for (int i = 0, j=0; i < 2; i++, j++) { System.out.println( i +" "+ j ); } As 0 < 2 is true (stated above), the compiler enters the for loop and prints the current values contained in the variables i and j to the screen: 0 0 Current Memory Snapshot i =0 j =0 =========4======= for (int i = 0, j=0; i < 2; i ++, j ++) { System.out.println(i+" "+j); } When the for block iteration completes its current iteration, the variables i and j get incremented to 1 because of the postfix operator '++'. Current Memory Snapshot i = 1 j = 1 =========5======= for (int i = 0, j=0; i < 2; i++, j++) { System.out.println(i+" "+j); } Check if the current value stored in variable i (i.e. 1) is less than the value 2. Answer: True ========6======== for (int i = 0, j=0; i < 2; i++, j++) { System.out.println( i +" "+ j ); } As 1 < 2 is true (stated above), the compiler enters the for loop and prints the current values contained in the variables i and j to the screen: 1 1 ========7======== for (int i = 0, j=0; i < 2; i ++, j ++) { System.out.println(i+" "+j); } When the for block iteration completes its current iteration, the variables i and j get incremented to 2 because of the postfix operator '++'. Current Memory Snapshot i = 2 j = 2 ========8======== for (int i = 0, j=0; i < 2; i++, j++) { System.out.println(i+" "+j); } Check if the current value stored in variable i (i.e. 2) is not less than the value 2. Answer: false Therefore, the for block gets exited.

Given: int j=0; do { if (10%2==0) { continue; } //more code// } while (j++>2); What is correct? (Choose all that apply) a) continue keyword breaks out of the do while block b) continue breaks out of the if block only c) continue breaks out of the if block and jumps down to the while condition d) none of the above

c) is correct, continue breaks out of the if block and jumps down to the while condition int j=0; do { if (10%2==0) { continue; } //more code// } while (j++>2); j++>2 Postfix operator j++ does not get incremented until after the expression is calculated i.e. j > 2 Then 'j' gets incremented.

Given: public class A { public static void main(String[] args) { String s = "-"; switch("RED".toLowerCase() ) { case "pink": s += "y"; case "red": s += "r"; case "green": s += "g"; } System.out.println(s); } } What is the result? A. - B. -r C. -rg D. Compilation fails E. An exception is thrown at runtime

c) is correct. It prints: -rg ===Code Step Through=== 1: public class A { 2: public static void main(String[] args) { 3: String s = "-"; 4: switch("RED".toLowerCase() ) { 5: case "pink": s += "y"; 6: case "red": s += "r"; 7: case "green": s += "g"; 8: } 9: System.out.println(s); 10: } 11: } String 's' is created and initialized with "-" ========2======= 1: public class A { 2: public static void main(String[] args) { 3: String s = "-"; 4: switch("RED".toLowerCase()){ 5: case "pink": s += "y"; 6: case "red": s += "r"; 7: case "green": s += "g"; 8: } 9: System.out.println(s); 10: } 11: } String "RED" is converted to "red" using method toLowerCase(). The string "red" is then passed into the switch block. =======3======== 1: public class A { 2: public static void main(String[] args) { 3: String s = "-"; 4: switch("RED".toLowerCase() ){ 5: case "pink": s += "y"; 6: case "red": s += "r"; 7: case "green": s += "g"; 8: } 9: System.out.println(s); 10: } 11: } On the line 5, the String "red" is not equal to "pink" therefore this case is skipped Snapshot of Variables in Memory: s = "-" =======4======= 1: public class A { 2: public static void main(String[] args) { 3: String s = "-"; 4: switch("RED".toLowerCase() ){ 5: case "pink": s += "y"; 6: case "red": s += "r"; 7: case "green": s += "g"; 8: } 9: System.out.println(s); 10: } 11: } On the line 6, the String "red" is equal to "red" stored in the variable s, therefore this case is executed s += "r" in which case the string value "r" is appended onto the string s. Snapshot of Variables in Memory: s = "-r" =======5======= 1: public class A { 2: public static void main(String[] args) { 3: String s = "-"; 4: switch("RED".toLowerCase() ){ 5: case "pink": s += "y"; 6: case "red": s += "r"; 7: case "green": s += "g"; 8: } 9: System.out.println(s); 10: } 11: } As noted above, the current string s value contains "-r" As there is no break between cases in the switch block, the program flow goes to the next case on the line 7 and executes it (irrespective of whether or not the case is true or false). s += "g". The current s value is "-r" which has appended to it g Snapshot of Variables in Memory: s = "-rg" =======6======= 1: public class A { 2: public static void main(String[] args) { 3: String s = "-"; 4: switch("RED".toLowerCase() ) { 5: case "pink": s += "y"; 6: case "red": s += "r"; 7: case "green": s += "g"; 8: } 9: System.out.println(s); 10: } 11: } The program flow exits the switch block on the line 8 and executes the instruction on the line 9. This outputs the contents of the variable s to the screen i.e. "-rg"

class A { static int i=1; public static void main(String[] args) { switch(i){ case 0: System.out.println("0"); break; case 1: System.out.println("1"); break; default: System.out.println("default"); } }} What is the result? (Choose all that apply) a) compiler error b) runtime error c) compile and print 1 d) none of the above

c) is correct. The program will print: 1 Note: We must declare static variables in the class and not method. The below would give compiler error: class A{ public static void main(String[] args) { static int i=1; switch(i){ case 0: System.out.println(i); break; case 1: System.out.println(i); break; default: System.out.println(i); } } }

Given: import java.io.IOException; class A { void m() throws IOException{} } import java.io.FileNotFoundException; public class B extends A { public void m() throws FileNotFoundException{ System.out.println("B"); }} What is the result? (Choose all that apply) a) compiler error b) runtime error c) compile and run fine d) none of the above

c) is correct. It will compile and run fine. The program will compile and run fine. This question tests your knowledge of constructors that throw exceptions. It is important to be familiar with the Exception Class Hierarchy for this question. Taking an aspect of the exception class hierarchy, we can see that the class Throwable is extended by Exception, which is extended by IOException which is extended by FileNotFoundException: Throwable ↑ extends ↑ Exception ↑ extends ↑ IOException ↑ extends ↑ FileNotFoundException Overriding methods can only throw the original exception (in this example: IOException) and/or subclass of the original Exception (in this case FileNotFoundException). Let's see how this is implemented in the code: 1: import java.io.IOException; 2: class A { 3: void m() throws IOException{} 4: } 5: import java.io.FileNotFoundException; 6: public class B extends A { 7: public void m() throws FileNotFoundException{ 8: System.out.println("B"); 9: }} On the line 3, we can see that the superclass class A method m() can throw an IOException. According to the rules of exception handling, the constructor in the subclass B can only throw: ➤ The original exception (in this case, IOException) and/or ➤ A superclass of the original exception (in this case, FileNotFoundException) On line 7, the overriding method m(), in class B, throws the FileNotFoundException exception, which is fine, as it is a subclass of the original exception thrown in class A (i.e. IOException). Note: If the subclass method m() threw IOException and/or Exception, it would give a compiler error.

Given: int i = 0; while (i<2) { label: if (i<2) { System.out.println("continue label"); i++; continue; } } What is the result? (Choose all that apply) a) compiler error b) runtime error c) compile and print "continue label" "continue label" d) none of the above

c) is correct. The program will compile and print: continue label continue label The keyword 'continue' only works to continue loops which is fine in this code: int i = 0; while (i<2) { label: if (i<2) { System.out.println("continue label"); i++; continue; } } ===Code Step Through=== 1: int i = 0; 2: while (i<2) { 3: label: 4: if (i<2) { 5: System.out.println("continue label"); 6: i++; 7: continue; 8: } 9: } Variable i is initialised to 0. =======2======= 1: int i = 0; 2: while ( i <2) { 3: label: 4: if (i<2) { 5: System.out.println("continue label"); 6: i++; 7: continue; 8: } 9: } The current value of the variable i is currently 0 and as 0 is less than 2 therefore the result is true and the while block is entered. =======3======= 1: int i = 0; 2: while ( i <2) { 3: label: 4: if ( i <2) { 5: System.out.println("continue label"); 6: i++; 7: continue; 8: } 9: } Inside the label of the while block, the current value of the variable i is currently 0 and as 0 is less than 2, therefore the result is true and the if block is entered. =======4======= 1: int i = 0; 2: while ( i <2) { 3: label: 4: if ( i <2) { 5: System.out.println("continue label"); 6: i++; 7: continue; 8: } 9: } Inside the if block, the string "continue label" is printed to the screen. =======5======= 1: int i = 0; 2: while ( i <2) { 3: label: 4: if ( i <2) { 5: System.out.println("continue label"); 6: i ++; 7: continue; 8: } 9: } The variable i is incremented by 1 using the postfix operator ++. ============== Snapshot of Variables in Memory: i = 1 =======6======= 1: int i = 0; 2: while ( i <2) { 3: label: 4: if ( i <2) { 5: System.out.println("continue label"); 6: i ++; 7: continue; 8: } 9: } The continue keyword gets executed which continues the next iteration of the while loop. ============== Snapshot of Variables in Memory: i = 1 =======7======= 1: int i = 0; 2: while ( i <2) { 3: label: 4: if (i<2) { 5: System.out.println("continue label"); 6: i++; 7: continue; 8: } 9: } The current value of the variable i is currently 1 and as 1 is less than 2 therefore the result is true and the while block is entered. =======8======= 1: int i = 0; 2: while ( i <2) { 3: label: 4: if ( i <2) { 5: System.out.println("continue label"); 6: i++; 7: continue; 8: } 9: } Inside the label of the while block, the current value of the variable i is currently 1 and as 1 is less than 2, therefore the result is true and the if block is entered. =======9======= 1: int i = 0; 2: while ( i <2) { 3: label: 4: if ( i <2) { 5: System.out.println("continue label"); 6: i++; 7: continue; 8: } 9: } Inside the if block, the string "continue label" is printed to the screen. =======10======= 1: int i = 0; 2: while ( i <2) { 3: label: 4: if ( i <2) { 5: System.out.println("continue label"); 6: i ++; 7: continue; 8: } 9: } The variable i is incremented by 1 using the postfix operator ++. ============== Snapshot of Variables in Memory: i = 2 =======11======= 1: int i = 0; 2: while ( i <2) { 3: label: 4: if ( i <2) { 5: System.out.println("continue label"); 6: i ++; 7: continue; 8: } 9: } The continue keyword gets executed which continues the next iteration of the while loop. ============== Snapshot of Variables in Memory: i = 2 =======12======= 1: int i = 0; 2: while ( i <2) { 3: label: 4: if (i<2) { 5: System.out.println("continue label"); 6: i++; 7: continue; 8: } 9: } The current value of the variable i is currently 2 and as 2 is not less than 2 therefore the result is true and the and the while block is skipped. Summary of output: continue label continue label

Given: class A { public static void main(String[] args) { try { throw new Exception(); } catch (Exception e1) { System.out.println("catch 1"); try { throw new Exception(); } catch (Exception e2) { System.out.println("catch 2"); } finally{ System.out.println("Inner finally"); } } finally{ System.out.println("Outer finally"); }}} What is the result? (Choose all that apply) a) compiler error b) runtime error c) compile and print: catch 1 catch 2 Inner finally Outer finally d) none of the above

c) is correct. The program will compile and print: catch 1 catch 2 Inner finally Outer finally This question tests your knowledge on try/catch blocks. In particular nested, try/catch blocks. You can use nesting try/catch blocks in your code as highlighted below: class A { public static void main(String[] args) { try { throw new Exception(); } catch (Exception e1) { System.out.println("catch 1"); try { throw new Exception(); } catch (Exception e2) { System.out.println("catch 2"); } finally{ System.out.println("Inner finally"); } } finally{ System.out.println("Outer finally"); } }} Let's step through the program see how it runs: ===Code Step Through=== 1: class A { 2: public static void main(String[] args) { 3: try { 4: throw new Exception(); 5: } 6: catch (Exception e1) { 7: System.out.println("catch 1"); 8: try { 9: throw new Exception(); 10: } catch (Exception e2) { 11: System.out.println("catch 2"); 12: } 13: finally{ 14: System.out.println("Inner finally"); 15: } 16: } 18: finally{ 19: System.out.println("Outer finally"); 20: } }} On the line 4, the first exception is thrown and is caught on the line 6. The "catch 1" statement is printed on the line 7. =======2======= 1: class A { 2: public static void main(String[] args) { 3: try { 4: throw new Exception(); 5: } 6: catch (Exception e1) { 7: System.out.println("catch 1"); 8: try { 9: throw new Exception(); 10: } catch (Exception e2) { 11: System.out.println("catch 2"); 12: } 13: finally{ 14: System.out.println("Inner finally"); 15: } 16: } 18: finally{ 19: System.out.println("Outer finally"); 20: } }} Inside the catch block, on the line 9, another exception thrown. =======3======= 1: class A { 2: public static void main(String[] args) { 3: try { 4: throw new Exception(); 5: } 6: catch (Exception e1) { 7: System.out.println("catch 1"); 8: try { 9: throw new Exception(); 10: } catch (Exception e2) { 11: System.out.println("catch 2"); 12: } 13: finally{ 14: System.out.println("Inner finally"); 15: } 16: } 18: finally{ 19: System.out.println("Outer finally"); 20: } }} This inner exception gets caught on the line 10 and "catch 2" is printed to screen on the line 11. After the catch block has completed, the finally block is entered on the line 13 and "Inner finally" is printed to screen on the line 14. =======4======= 1: class A { 2: public static void main(String[] args) { 3: try { 4: throw new Exception(); 5: } 6: catch (Exception e1) { 7: System.out.println("catch 1"); 8: try { 9: throw new Exception(); 10: } catch (Exception e2) { 11: System.out.println("catch 2"); 12: } 13: finally{ 14: System.out.println("Inner finally"); 15: } 16: } 18: finally{ 19: System.out.println("Outer finally"); 20: } }} After the inner finally block is printed, the code jumps out of the catch (Exception e1) block and into the outer finally block. Inside the outer finally Outer finally is printed on the line 19. Then the code completes. Final output: catch 1 catch 2 Inner finally Outer finally

Given: class A { public static void main(String[] args) { int i = 0; String val; switch(i){ case 0: default: val = "def"; } System.out.println(val); }} What is the result? (Choose all that apply) a) compiler error b) runtime error c) compile and print def d) none of the above

c) is correct. The program will compile and print: "def" 1: class A { 2: public static void main(String[] args) { 3: int i = 0; 4: String val; 5: switch( i ){ 6: case 0: 7: default: val = "def"; 8: } 9: System.out.println(val); 10: }} As there is no break in the case 0, the compiler knows that the variable 'val' declared on the line 4, will always be initialized on the line 7. Note: 'case' doesn't need a statement after it

Given: public static void main(String[] args) { int i = 0; String s; switch(i){ case 0: default: s="default"; } System.out.print(s); } What is the result? (Choose all that apply) a) compiler error b) runtime error c) compile and print default d) none of the above

c) is correct. The program will compile and print: default. public static void main(String[] args) { int i = 0; String s; switch(i){ case 0: default: s="default"; } System.out.print(s); } Local variables in methods (either static methods or nonstatic methods) must be initialized. Local variable 's' was not initialized. However, as there is no break in the switch block this will compile and run fine and initialize 's' with string value default.

Given: import java.io.IOException; class A { public A() throws IOException{} } import java.io.FileNotFoundException; public class B extends A { public B() throws Throwable{} } What is the result? (Choose all that apply) a) compiler error b) runtime error c) compile and run fine d) none of the above

c) is correct. The program will compile and run fine. This question tests your knowledge of constructors that throw exceptions. It is important to be familiar with the Exception Class Hierarchy for this question. Taking an aspect of the exception class hierarchy, we can see that the class Throwable is extended by Exception, which is extended by IOException which is extended by FileNotFoundException: Throwable ↑ extends ↑ Exception ↑ extends ↑ IOException ↑ extends ↑ FileNotFoundException Subclass constructors can only throw the original exception (in this example: IOException) and/or a superclass of the original Exception (in this case Exception and/or Throwable). Let's see how this is implemented in the code: 1: import java.io.IOException; 2: class A { 3: public A() throws IOException{} 4: } 5: import java.io.FileNotFoundException; 6: public class B extends A { 7: public B() throws Throwable{} 8: } On the line 3, we can see that the superclass constructor (in class A) can throw an IOException. According to the rules of exception handling, the constructor in the subclass B can only throw: ➤ The original exception (in this case, IOException) and/or ➤ A superclass of the original exception (in this case, Exception and/or Throwable) On line 7, the constructor in class B throws the Throwable exception, which is fine, as it is a superclass of the original exception thrown in class A (i.e. IOException). Note: If the subclass constructor, in class B, threw a subclass of IOException (in this case, FileNotFoundException) it would give a compiler error.

Given: if (true) { System.out.println("true"); if (true) System.out.println("true true"); else{ System.out.println("false"); } } Assuming the above compiles and runs correctly what is the output? a) true b) true true c) true true true d) none of the above

c) is correct. The program will print: true true true Dangling Else Problem The inner if owns the else clause: if (true) { System.out.println("true"); if (true) System.out.println("true true"); else{ System.out.println("false"); } }

Which of the following will compile? (Choose all that apply) a) int i = 0; switch(i){ case 0: System.out.println(); break; case 0: System.out.println(); break; } b) int i = 0; switch(i){ case 0{ System.out.println();}; } c) Integer i = new Integer(0); switch(i){ case 0:{ System.out.println("Hi");}; } d) Integer i = new Integer(0); switch(i){ case new Integer(0):{ System.out.println("Hi");}; }

c) is correct. ➤ c) Integer i = new Integer(0); switch( i ){ case 0:{ System.out.println("Hi");}; } Wrapper class Integer 'i' auto-unboxes to primitive type int and is compared to case 0 ok The Following Will Not Compile: ➤ a) int i = 0; switch(i){ case 0: System.out.println(); break; case 0: System.out.println(); break; } You can't have more than one case label the same. ➤ b) int i = 0; switch(i){ case 0{ System.out.println();}; } Missing ' : ' therefore compiler error ➤ d) Integer i = new Integer(0); switch(i){ case (new Integer(0)):{ System.out.println("Hi");}; } Compiler Error: A constant is required

Given: int y=0; do { System.out.print(y); y++; } while (y<2); What is the result? (Choose all that apply) a) compiler error b) runtime error c) compile and print 01 d) none of the above

c) is true. The program will compile and print: 01 ===Code Step Through=== int y=0; do { System.out.print(y); y++; } while (y<2); Variable y gets initialized to 0 ========2======== int y=0; do { System.out.print(y); y++; } while (y<2); The while loop is entered and the contents of the variable y get printed to the screen: 0 ========3======== int y=0; do { System.out.print(y); y++; } while (y<2); A postfix increment operation is undertaken on y variable. The postfix operator means the value of y does not get incremented until AFTER the line where y++ gets executed ===================== Current value stored in memory after y++ is executed: y = 1 ==========4=========== int y=0; do { System.out.print(y); y++; } while (y<2); One is less than two, therefore the condition is true move to the next iteration of the while loop. ===================== Current value stored in memory: y = 1 ========5======== int y=0; do { System.out.print(y); y++; } while (y<2); The while loop is entered and the contents of the variable y get printed to the screen 1 ========6======== int y=0; do { System.out.print(y); y++; } while (y<2); A postfix increment operation is undertaken on y variable. The postfix operator means the value of y does not get incremented until AFTER the line where y++ gets executed. ===================== Current value stored in memory after y++ line executed: y = 2 ==========7=========== int y=0; do { System.out.print(y); y++; } while (y<2); Is y less than 2? 2 < 2 Two is not less than two, therefore the condition is false therefore skip the while loop

Which of the following types cannot be used in a switch statement? (Choose all that apply) a) Byte b) byte c) float d) double e) int f) integer

d) is correct. Primitive type 'double' cannot be passed into a switch statement. This question tests your knowledge of variable types used with switch block code. To help memorize the types that can be used in a switch statement, the following acronym may help remember: CB-SIS-E char or Character byte or Byte short or Short int or Integer String enum Note: Primitive types are represented in lowercase e.g. int, char etc. Wrapper types are represented the first letter in uppercase e.g. Character, Byte etc

Which of the following will compile? (Choose all that apply) a) int i=0; while (i=2) { System.out.println(i); } b) int i=0; while (i++) { System.out.println(i); } c) for (int i; i < 2; i++) { System.out.println("i"); } d) int i = 0; while (i==0) { System.out.println("0"); } e) int i; while (i==0) { System.out.println("0"); } f) int i=0; for (int i = 0; i < 2; i++) { } g) public static void main(String[] args) { for (int i = 0; i < 2; i++) { } for (int i = 0; i < 2; i++) { } }

d) and g) are correct. ➤ d) int i = 0; while (i==0) { System.out.println("0"); } You can compare variables inside while condition. ➤ g) public static void main(String[] args) { for (int i = 0; i < 2; i++) { } for (int i = 0; i < 2; i++) { } } The scope of variables declared within a loop block is within the loop block only. Therefore you can declare a variable same name in different loop blocks. The Following Will Not Compile: a) int i=0; while (i = 2) { System.out.println(i); } while loop's only take boolean expressions assigning '=' a value to a variable inside a while loop condition will give a compiler error b) int i=0; while ( i++) { System.out.println(i); } incrementing the variable inside the while loop condition will give a compiler error c) for (int i ; i < 2; i++) { System.out.println("i"); } Not initializing a variable inside the loop condition will give a compiler error e) int i ; while (i==0) { System.out.println("0"); } Not initializing a variable to used in a loop condition will give a compiler error f) int i = 0; for (int i = 0; i < 2; i++) { } int i is declared above the for loop and then re-declared in the for loop which gives a compiler error. Soluion: int i = 0; for (i = 0; i < 2; i++) { }

Which of the following will compile? (Choose all that apply) a) int x = 0; while (false) { x=3; } b) int x=1; if (false){x=3;} c) int x = 0; for (int i = 0; false; i++) { x=3; } d) none of the above

d) is correct They all give compiler errors with unreachable statements. a) int x = 0; while (false) { x=3; } b) int x=1; if (false){x=3;} c) int x = 0; for (int i = 0; false; i++) { x=3; }

A recursive method call to itself, which doesn't stop, can cause what kind of in the exception? (Choose all that apply) a) AssertionError b) IOException c) OutOfMemoryError d) StackOveflowException

d) is correct. A recursive method call to itself, which doesn't stop, will eventually cause a StackOveflowException. Parameters and local variables are allocated memory on the stack heap near the top. Processes/Methods are allocated memory on the bottom end of the stack heap. A recursive call that never ends, results in the top of the stack keep colliding with the bottom of the stack keep which results in a StackOveflowException.

Given: public class A { public static void main(String[] args) { foreach: for(int j=0; j<2; j++) { for(int k=0; k< 2; k++) { System.out.print(" " + j); if(j== 1 && k== 1) break foreach; if (j== 0 || j== 2) break; } }}} What is the result? (Choose all that apply) a) compiler error b) runtime error c) compile and print 0 1 d) none of the above

d) is correct. It will print 0 1 1 This question tests your knowledge of nested 'for loops' and also the use of logical AND/OR operators. It would be highly advisable to use a piece of rough work paper, pencil and eraser in answering these questions. Swiftly write out a very brief schematic of the variables and program flow blocks, then step through each line of the code as if you were the compiler. ===Code Step Through=== 1: public class A { 2: public static void main(String[] args) { 3: foreach: 4: for(int j =0; j<2; j++) { 5: for(int k=0; k< 2; k++) { 6: System.out.print(" " + j); 7: if(j== 1 && k== 1) break foreach; 8: if (j== 0 || j== 2) break; 9: } 10: } } } On the line 3, the 'foreach' label block is entered, which contains the two nested 'for loops'. On the line 4, inside the outer 'for loop', the variable j is initialised to 0. Below is a snapshot of the contents of the variables in memory at this point in time when the code is running: ===Memory Snapshot=== Outer j = 0 Inner k = None Current Output: None ===========2============= 1: public class A { 2: public static void main(String[] args) { 3: foreach: 4: for(int j =0; j <2; j++) { 5: for(int k=0; k< 2; k++) { 6: System.out.print(" " + j); 7: if(j== 1 && k== 1) break foreach; 8: if (j== 0 || j== 2) break; 9: } 10: } } } On the line 4, the current value of external variable j is checked to see if it is less than 2. As the current value of the outer variable j contains 0 and 0 is less than 2, then the outer for loop block is entered. The following is a snapshot of the contents of the variables in memory at this particular state in time of the program flow control. As stated above, when writing out the program flow on paper, it would be advisable to write these variables at the top of the page and to update the contents of the variables as you manually go through the program flow control (code run). ===Memory Snapshot=== Outer j = 0 Inner k = None Current Output: None ===========3============= 1: public class A { 2: public static void main(String[] args) { 3: foreach: 4: for(int j =0; j <2; j++) { 5: for(int k=0; k< 2; k++) { 6: System.out.print(" " + j); 7: if(j== 1 && k== 1) break foreach; 8: if (j== 0 || j== 2) break; 9: } 10: } } } On the line 5, in the inner nested 'for loop', the contents of the inner variable k is initialised to 0. The current state of the contents of all the variables in memory are updated accordingly below: ===Memory Snapshot=== Outer j = 0 Inner k = 0 Current Output: None ===========4============= 1: public class A { 2: public static void main(String[] args) { 3: foreach: 4: for(int j =0; j <2; j++) { 5: for(int k=0; k< 2; k++) { 6: System.out.print(" " + j); 7: if(j== 1 && k== 1) break foreach; 8: if (j== 0 || j== 2) break; 9: } 10: } } } On the line 5, the current value of the inner variable k is checked to see if it is less than 2. As the current value of the inner variable k contains 0 and as 0 is less than 2, the condition is true and the inner 'for' loop block is entered. ===Memory Snapshot=== Outer j = 0 Inner k = 0 Current Output: None ===========5============= 1: public class A { 2: public static void main(String[] args) { 3: foreach: 4: for(int j =0; j <2; j++) { 5: for(int k=0; k< 2; k++) { 6: System.out.print(" " + j ); 7: if(j== 1 && k== 1) break foreach; 8: if (j== 0 || j== 2) break; 9: } 10: } } } On the line 6, the current value of the outer loop variable j is printed to the output stream (screen): 0 The current state of the contents of the variables in memory are updated accordingly below: ===Memory Snapshot=== Outer j = 0 Inner k = 0 Current Output: 0 ==========6============== 1: public class A { 2: public static void main(String[] args) { 3: foreach: 4: for(int j =0; j <2; j++) { 5: for(int k=0; k< 2; k++) { 6: System.out.print(" " + j ); 7: if( j == 1 && k== 1) break foreach; 8: if (j== 0 || j== 2) break; 9: } 10: } } } On the line 7, the current value stored in the variable j is compared to see if it is equal to 1. Referencing the memory snapshot above, the current value stored in j is 0 and 0 is not equal to 1, then the condition is false and the 'if block' is skipped and program flow jumps to line 8. Note: The second operand of this 'if block' is not checked because of logical short circuiting (see notes below). ===Memory Snapshot=== Outer j = 0 Inner k = 0 Current Output: 0 ===========7============= 1: public class A { 2: public static void main(String[] args) { 3: foreach: 4: for(int j =0; j <2; j++) { 5: for(int k=0; k< 2; k++) { 6: System.out.print(" " + j ); 7: if(j== 1 && k== 1) break foreach; 8: if ( j == 0 || j== 2) break; 9: } 10: } } } On the line 8, the current value stored in j is equal to 0, therefore the condition is true and the 'if block' (on the line 8) is entered. Note: The second operand of this if block is not checked because of logical short circuiting (see notes below). Inside the 'if block', on the line 8, a 'break' is executed which means program flow control breaks out of the inner 'for loop' block. As a consequence, all variables in the inner 'for loop' are erased from memory. As the inner for loop was exited in the first iteration, the inner variable 'k' did not have an opportunity to increment. Therefore, it's contents are reset to 0. ===Memory Snapshot=== Outer j = 0 Inner k = 0 Current Output: 0 ==========8============== 1: public class A { 2: public static void main(String[] args) { 3: foreach: 4: for(int j =0; j <2; j++) { 5: for(int k=0; k< 2; k++) { 6: System.out.print(" " + j ); 7: if(j== 1 && k== 1) break foreach; 8: if (j== 0 || j== 2) break; 9: } 10: } 🠄 } } On the line 10, the outer variable j is incremented by 1. This is undertaken by the postfix operator j++ being called on the line 4. Below is a snapshot of the current contents of the variables in memory after the above aspect of the code is executed: ===Memory Snapshot=== Outer j = 0 Inner k = 0 Current Output: 0 ===========9============= 1: public class A { 2: public static void main(String[] args) { 3: foreach: 4: for(int j =0; j <2; j++) { 5: for(int k=0; k< 2; k++) { 6: System.out.print(" " + j ); 7: if(j== 1 && k== 1) break foreach; 8: if (j== 0 || j== 2) break; 9: } 10: } } } On the line 4, the current value stored in j is 1: ===Memory Snapshot=== Outer j = 1 Inner k = 0 Current Output: 0 As the current value of the variable j equals 1 is less than 2, then the condition is true and the outer 'for loop' is entered. =======10======= 1: public class A { 2: public static void main(String[] args) { 3: foreach: 4: for(int j =0; j <2; j++) { 5: for(int k=0; k< 2; k++) { 6: System.out.print(" " + j ); 7: if(j== 1 && k== 1) break foreach; 8: if (j== 0 || j== 2) break; 9: } 10: } } } On the line 5, the inner for k value is re-initialised to 0. ===Memory Snapshot=== Outer j = 1 Inner k = 0 Current Output: 0 ==========11============ 1: public class A { 2: public static void main(String[] args) { 3: foreach: 4: for(int j =0; j <2; j++) { 5: for(int k=0; k< 2; k++) { 6: System.out.print(" " + j ); 7: if(j== 1 && k== 1) break foreach; 8: if (j== 0 || j== 2) break; 9: } 10: } } } On the line 5, the current value of the variable k contains a 0 and as 0 is less than 2, the condition is true and the inner for loop block is entered. =======12======= 1: public class A { 2: public static void main(String[] args) { 3: foreach: 4: for(int j =0; j <2; j++) { 5: for(int k=0; k< 2; k++) { 6: System.out.print(" " + j ); 7: if(j== 1 && k== 1) break foreach; 8: if (j== 0 || j== 2) break; 9: } 10: } } } On the line 6, the current value of variable j is printed to the screen i.e. 1. Below is a snapshot of the current contents of the variables in memory after the above aspect of the code is executed: ===Memory Snapshot=== Outer j = 1 Inner k = 0 Current Output: 0 1 ==========13============ 1: public class A { 2: public static void main(String[] args) { 3: foreach: 4: for(int j =0; j <2; j++) { 5: for(int k=0; k< 2; k++) { 6: System.out.print(" " + j ); 7: if( j == 1 && k== 1) break foreach; 8: if (j== 0 || j== 2) break; 9: } 10: } } } On the line 7, the current value stored in the outer variable j is 1, and as 1 is equal to 1, the left hand side of the '&&' operator is true. As the left hand side of the '&&' operator is true, the right hand side of the operator must also be checked. Moving onto the right-hand side of the operator, the inner variable k is 0 and as 0 is not equal to 1, then the result of the left-hand side of the operator is false. As true && false results in the overall condition being false, the 'if block' (on the line 7) is skipped. ===Memory Snapshot=== Outer j = 1 Inner k = 0 Current Output: 0 1 ==========14============ 1: public class A { 2: public static void main(String[] args) { 3: foreach: 4: for(int j =0; j <2; j++) { 5: for(int k=0; k< 2; k++) { 6: System.out.print(" " + j ); 7: if(j== 1 && k== 1) break foreach; 8: if ( j == 0 || j == 2) break; 9: } 10: } } } On the line 8, the current contents of the outer variable j is 1 and as 1 is not equal to 0, the result on the left-hand side of the '||' operator is false. As a consequence of the left-hand side of the '||' operator being evaluated to false, it is necessary for the right hand side of the '||' operator to be also checked (See operand short circuits below). On the right-hand side of the '||' operator, the current contents of the variable j is 1 and as 1 is not equal to 2, the 'if block' on the line 8 is skipped. ===Memory Snapshot=== Outer j = 1 Inner k = 0 Current Output: 0 1 ===========15=========== 1: public class A { 2: public static void main(String[] args) { 3: foreach: 4: for(int j =0; j <2; j++) { 5: for(int k=0; k< 2; k++) { 6: System.out.print(" " + j ); 7: if(j== 1 && k== 1) break foreach; 8: if (j== 0 || j== 2) break; 9: } 🠄 10: } } } On the line 9, at end of current inner loop iteration, the current value stored in the variable k is incremented by 1 using the postfix operator k++ on the line 5. Below is a snapshot of the contents of the variables in memory after the above aspect of the code has been executed: ===Memory Snapshot=== Outer j = 1 Inner k = 1 Current Output: 0 1 ==========16============ 1: public class A { 2: public static void main(String[] args) { 3: foreach: 4: for(int j =0; j <2; j++) { 5: for(int k=0; k< 2; k++) { 6: System.out.print(" " + j ); 7: if(j== 1 && k== 1) break foreach; 8: if (j== 0 || j== 2) break; 9: } 10: } } } On the line 5, the current value stored in the variable k is 1 and as 1 is less than 2, the result is true and the inner for loop is entered. ===Memory Snapshot=== Outer j = 1 Inner k = 1 Current Output: 0 1 ==========17============ 1: public class A { 2: public static void main(String[] args) { 3: foreach: 4: for(int j =0; j <2; j++) { 5: for(int k=0; k< 2; k++) { 6: System.out.print(" " + j ); 7: if(j== 1 && k== 1) break foreach; 8: if (j== 0 || j== 2) break; 9: } 10: } } } On the line 6, the current value stored in the variable j is printed to the screen. i.e. 1 ===Memory Snapshot=== Outer j = 1 Inner k = 1 Current Output: 0 1 1 ===========18=========== 1: public class A { 2: public static void main(String[] args) { 3: foreach: 4: for(int j =0; j <2; j++) { 5: for(int k=0; k< 2; k++) { 6: System.out.print(" " + j); 7: if( j == 1 && k== 1) break foreach; 8: if (j== 0 || j== 2) break; 9: } 10: } } } On the line 7, as the current value stored in j is 1 and 1 is equal to 1, then the condition on the left-hand side of the '&&' is true. On the right-hand side of the '&&' operator, the current value stored in the variable k is 1 and as 1 is equal to 1, the right-hand side of the '&&' is also true. As true && true equals true, the if block is entered. ===Memory Snapshot=== Outer j = 1 Inner k = 1 Current Output: 0 1 1 ==========19============ 1: public class A { 2: public static void main(String[] args) { 3: foreach: 4: for(int j =0; j <2; j++) { 5: for(int k=0; k< 2; k++) { 6: System.out.print(" " + j); 7: if( j == 1 && k== 1) break foreach; 8: if (j== 0 || j== 2) break; 9: } 10: } } 🠄} On the line 7, a break is executed which breaks out of the 'foreach' label block. This means that program flow control breaks out of the nested 'for' loop and jumps to the line after line 10 resulting in the programme ending. Final output: 0 1 1 Note 1: foreach: block contains both the outer and inner for loop blocks. Note 2: You will need to memorize this table for the exam: A B---A&&B---- A||B T T -----T----------T T F -----F---------T F T-----F----------T F F-----F----------F Short-Circuit - Boolean Operators One of the aspects that you will also need to know for the exam is the short-circuit evaluation of boolean operators. This short-circuiting for the '&&' and '||' operators are explained below: Logical '&&' Short-Circuit: Let's look at the highlighted aspects of the table which outlines the logical '&&' short-circuit: A B---A&&B T T ------T T F ------F F T------F F F------F Looking at the table above, if A is false (F), then the operator '&&' does not check the value of Bto see whether or not it is true (T) or false (F), it simply short-circuits to the result to false (F). Logical '||' Short-Circuit: Likewise, looking at the highlighted aspects of the table which outlines the logical '||' short-circuit: A B-----A||B T T ------T T F ------T F T ------T F F ------F Likewise, looking at the table above, if A is false (T), then the operator '||' doesn't check the value of B to see whether or not it is true (T) or false (F), it simply short-circuits to the result to true (T). Note: Bitwise operators like & | ^ are not on the exam Java 6 Java 7 Java 8

Given: int i = 2; switch(i){ default: System.out.println("default"); case 1: System.out.println("1"); case 0: System.out.println("0"); break; } What is the result? a) compiler error b) compile and print 1 c) compile and print 1 0 d) None of the above

d) is correct. None are correct. It will print "default" and then fall through the case blocks as there is no break in each of the cases - only at end, which is irrelevent. int i = 2; switch(i){ default: System.out.println("default"); case 1: System.out.println(" 1 "); case 0: System.out.println(" 0 "); break; } Prints: default 1 0 Note: default can be placed anywhere in a switch statement

Given: int i = 2; switch(i){ case 1: System.out.println("1"); default: System.out.println("default"); case 0: System.out.println("0"); break; } What is the result? a) compiler error b) compile and print 1 c) compile and print 1 default 0 d) None of the above

d) is correct. None are correct. int i = 2; switch( i ){ case 1: System.out.println("1"); default: System.out.println("default"); case 0: System.out.println("0"); break; } There is no case to match variable i and there is no break in the default so it prints: default 0

Given: byte b = 126; switch(b){ case 'b': System.out.println("b"); break; case 80: System.out.println("1"); break; case -2: System.out.println("2"); break; default: System.out.println("default"); } What is the result? a) compiler error b) runtime error c) compile and print default d) none of the above

d) is correct. None of the answers are correct. byte b = 126; switch(b){ case 'b': System.out.println("b"); break; case 80: System.out.println("1"); break; case -2: System.out.println("2"); break; default: System.out.println("default"); } The above are constants. According to the rules of Primitive Type Conversion, the above variables must be casted. However, as 'b', 80 and -2 are constants, therefore they don't need casting. Note: The Rules for Primitive Type Conversions are an essential aspect of the exam and will pop up regularly in questions. Primitive type conversion rules are comprised of: ➤Rules for Widening (not requiring casting) ➤Rules for Narrowing (requiring casting) In the case of Widening Type Conversion (i.e. not requiring casting), the following suggested abbreviation should be memorised for the exam: "b-silfd" where: b = byte, s = short, i = int, l = long, f = float, d = double With the above abbreviation, you can derive the following Widening Type Conversion "Tree" (it's best advised to memorise this for the exam as a reference) Widening Type Conversion "Tree" (not requiring casting): byte to short, int, long, float, double .................. ↲ short to int, long float, double .................. ↲ int to long float, double .............. ↲ long to float, double .................. ↲ float to double. In other words, when converting the above e.g. converting from byte to short, a cast is notneeded. As an example: byte b1 = 13; short s1 = b1 ; System.out.println(s1); The above will output: 13 byte to short What this means is that a byte value can be assigned to a short type without casting. This is called Widening Type Conversion. =================== The opposite of the above is termed Narrowing Type Conversion In the case of Narrowing Type Conversion (i.e. requiring casting), the following suggested abbreviation should be memorised for the exam : "dbs-cilf" where: d = double, b =byte, s = short, c = char, i = int, l = long, f = float, With the above abbreviation, you can derive the following Narrowing Type Conversion 'Tree'(it's best advised to memorise this for the exam as a reference): Narrowing Type Conversion 'Tree' (requiringcasting): double to byte, short, char, int, long, float ............................................................................. ↲ float to byte to short, char, int, long ................................................................ ↲ long to byte to short, char, int ........................................................ ↲ int to byte, short, char ................................... ↲ charto byte, short. .......................... ↲ short to byte or char. In other words, when converting the above, a cast is required. For instance converting from an int to byte type or a short to char type requires casting. As an example: byte b4 = 4; byte b5 = ( byte ) (b4+4); System.out.println(b5); When the addition operation is executed between b4 + 4, the result value (8) is of primitive type int This int value needs to be casted to byte to store byte value from the Narrowing Primitive Type 'tree': int to byte, short, char. By casting, the resultant output would be: 8

Given: char c = '0'; switch(c++){ case '0': System.out.println("0"); break; case 1: System.out.println("1"); break; case 2: System.out.println("2"); break; default: System.out.println("default"); } What is the result? (Choose all that apply) a) compiler error b) runtime error c) compile and print 1 d) none of the above

d) is correct. None of the answers are correct. char c = '0'; switch(c++){ case '0': System.out.println("0"); break; case 1: System.out.println("1"); break; case 2: System.out.println("2"); break; default: System.out.println("default"); } In the above code, switch(c++), the char 'c' gets incremented after the switch is executed. Therefore: case '0' gets executed and prints: "0"

Given: public class A { static int x = 7; public static void main(String [] args) { String s = ""; for(int y = 0; y < 2; y++) { x++; switch(x) { case 8: s += "8 "; case 9: s += "9 "; case 10: { s += "10"; break; } default: s += "d"; case 13: s+= "13"; } } System.out.println(s); } static { x++; } } What is the result? a) compiler error b) runtime error c) compile and print 8 9 1010 d) none of the above

d) is correct. None of the suggested answers are correct. The program will compilable and print: 9 1010 ===Code Step Through=== 1: public class A { 2: static int x = 7; 3: public static void main(String [] args) { 4: String s = ""; 5: for(int y = 0; y < 2; y++) { 6: x++; 7: switch(x) { 8: case 8: s += "8 "; 9: case 9: s += "9 "; 10: case 10: { s += "10"; break; } 11: default: s += "d"; 12: case 13: s+= "13"; 13: } 14: } 15: System.out.println(s); 16: } 17: static { x++; } 18: } On the line 2, the static variable x gets initialized first. Program flow then jumps to line 17 which results in static initialization block getting intialised. Inside this static block, the variable x gets incremented to 8. =======2======= 1: public class A { 2: static int x = 7; 3: public static void main(String [] args){ 4: String s = ""; 5: for(int y = 0; y < 2; y++) { 6: x++; 7: switch(x) { 8: case 8: s += "8 "; 9: case 9: s += "9 "; 10: case 10: { s += "10"; break; } 11: default: s += "d"; 12: case 13: s+= "13"; 13: } 14: } 15: System.out.println(s); 16: } 17: static { x++; } 18: } On the line 4 in the main method, String s gets initialized with an empty string. Program flow jumps to line 5, entering the for loop, y is initialized to 0. Then the current value of y (i.e. 0) is compared to check if it is less than '2' (y < 2). As 0<2, program flow enters the for loop. ========3======== 1: public class A { 2: static int x = 7; 3: public static void main(String [] args){ 4: String s = ""; 5: for(int y = 0; y < 2; y++) { 6: x++; 7: switch(x) { 8: case 8: s += "8 "; 9: case 9: s += "9 "; 10: case 10: { s += "10"; break; } 11: default: s += "d"; 12: case 13: s+= "13"; 13: } 14: } 15: System.out.println(s); 16: } 17: static { x++; } 18: } On the line 6, the variable x has a postfix operator which results in x getting incremented to 9 AFTER line 6. (Note: 'x' was already incremented by 1 in the static block on line 17). ========4======== 1: public class A { 2: static int x = 7; 3: public static void main(String [] args){ 4: String s = ""; 5: for(int y = 0; y < 2; y++) { 6: x++; 7: switch(x) { 8: case 8: s += "8 "; 9: case 9: s += "9 "; 10: case 10: { s += "10"; break; } 11: default: s += "d"; 12: case 13: s+= "13"; 13: } 14: } 15: System.out.println(s); 16: } 17: static { x++; } 18: } On the line 7, x contains value 9 and jumps into the switch block. ========5======== 1: public class A { 2: static int x = 7; 3: public static void main(String [] args){ 4: String s = ""; 5: for(int y = 0; y < 2; y++) { 6: x++; 7: switch(x) { 8: case 8: s += "8 "; 9: case 9: s += "9 "; 10: case 10: { s += "10"; break; } 11: default: s += "d"; 12: case 13: s+= "13"; 13: } 14: } 15: System.out.println(s); 16: } 17: static { x++; } 18: } Inside the switch block, x skips case 8, as it doesn't match. x matches case 9 and jumps into that case 9 block. Inside the case 9 block, "9 " is appended to string s Current values stored in memory: x = 9 s = "9 " y = 0 (Note: Keep a record of these values written down as you step through the code) =========6============ 1: public class A { 2: static int x = 7; 3: public static void main(String [] args){ 4: String s = ""; 5: for(int y = 0; y < 2; y++) { 6: x++; 7: switch(x) { 8: case 8: s += "8 "; 9: case 9: s += "9 "; 10: case 10: { s += "10"; break; } 11: default: s += "d"; 12: case 13: s+= "13"; 13: } 14: } 15: System.out.println(s); 16: } 17: static { x++; } 18: } As there is no break in case 9, flow control jumps to case 10 and appends string value "10" to s. Current values stored in memory: x = s = "9 10" y = 0 ==========7=========== 1: public class A { 2: static int x = 7; 3: public static void main(String [] args){ 4: String s = ""; 5: for(int y = 0; y < 2; y++) { 6: x++; 7: switch(x) { 8: case 8: s += "8 "; 9: case 9: s += "9 "; 10: case 10: { s += "10"; break; } 11: default: s += "d"; 12: case 13: s+= "13"; 13: } 14: } 🠄 15: System.out.println(s); 16: } 17: static { x++; } 18: } Program flow then breaks out of switch to line 13. On line 14, the y variable in the for loop, gets incremented to 1 (the y++ postfix operation on line 5 gets executed at the end of the for loop). Current values stored in memory: x = 9 s = "9 10" y = 1 ==========8=========== 1: public class A { 2: static int x = 7; 3: public static void main(String [] args) { 4: String s = ""; 5: for(int y = 0; y < 2; y++) { 6: x++; 7: switch(x) { 8: case 8: s += "8 "; 9: case 9: s += "9 "; 10: case 10: { s += "10"; break; } 11: default: s += "d"; 12: case 13: s+= "13"; 13: } 14: } 15: System.out.println(s); 16: } 17: static { x++; } 18: } Then the current value of y (which is 1) is compared to check if it is less than 2 (i.e. y < 2). As 1 < 2, program flow enters the for loop. ==========9=========== 1: public class A { 2: static int x = 7; 3: public static void main(String [] args){ 4: String s = ""; 5: for(int y = 0; y < 2; y++) { 6: x++; 7: switch(x) { 8: case 8: s += "8 "; 9: case 9: s += "9 "; 10: case 10: { s += "10"; break; } 11: default: s += "d"; 12: case 13: s+= "13"; 13: } 14: } 15: System.out.println(s); 16: } 17: static { x++; } 18: } On the line 6, the variable x has a postfix operator which results in x getting incremented to 10 AFTER line 6. On the line 7, the x value (which is currently 10) is passed into the switch block. Current values stored in memory: x = 9 s = "9 10" y = 1 ==========10=========== 1: public class A { 2: static int x = 7; 3: public static void main(String [] args){ 4: String s = ""; 5: for(int y = 0; y < 2; y++) { 6: x++; 7: switch(x) { 8: case 8: s += "8 "; 9: case 9: s += "9 "; 10: case 10: { s += "10"; break; } 11: default: s += "d"; 12: case 13: s+= "13"; 13: } 14: } 15: System.out.println(s); 16: } 17: static { x++; } 18: } Inside the switch block, x gets incremented to 10: Current values stored in memory: x = 10 s = "9 10" y = 1 Program flow control skips case 8 and case 9 as they dont match. x matches case 10 and jumps into that case 10 block. Inside the case 10 block, "10" is appended to string s. Current values stored in memory: x = 10 s = "9 1010" y = 1 ==========11=========== 1: public class A { 2: static int x = 7; 3: public static void main(String [] args){ 4: String s = ""; 5: for(int y = 0; y < 2; y++) { 6: x++; 7: switch(x) { 8: case 8: s += "8 "; 9: case 9: s += "9 "; 10: case 10: { s += "10"; break; } 11: default: s += "d"; 12: case 13: s+= "13"; 13: } 14: } 🠄 15: System.out.println(s); 16: } 17: static { x++; } 18: } Program flow then breaks out of switch and jumps to line 13. On line 14, the y variable in the for loop, gets incremented to 2 (the y++ postfix operation on line 5 gets executed at the end of the for loop). Current values stored in memory: x = 10 s = "9 1010" y = 2 ==========12=========== 1: public class A { 2: static int x = 7; 3: public static void main(String [] args) { 4: String s = ""; 5: for(int y = 0; y < 2; y++) { 6: x++; 7: switch(x) { 8: case 8: s += "8 "; 9: case 9: s += "9 "; 10: case 10: { s += "10"; break; } 11: default: s += "d"; 12: case 13: s+= "13"; 13: } 14: } 15: System.out.println(s); 16: } 17: static { x++; } 18: } Then the current value of y (which is 2) is compared to check if it is less than 2 (i.e. y < 2). As '2' not less than 2, program flow skips the for loop and jumps to line 15. On line 15, the value stored in string s is printed to the screen: "9 1010"

Given: class A { void mA() throws Exception{ try { throw new Exception(); } catch (Exception e) { System.out.println("Inside catch Exception"); throw new java.io.IOException(); } catch (Throwable t) { System.out.println("Inside catch throwable"); } finally{ System.out.println("Inside finally"); }} public static void main(String[] args) throws Exception { A a = new A(); a.mA(); }} Considering the above code will compile what is the output? What is the result? a) compiler error b) runtime error c) compile and print: Inside catch Exception Inside catch throwable Inside finally Exception in thread "main" java.io.IOException d) none of the above

d) is correct. The answer will be none of the suggested choices. The code will run fine and the output will be: Inside catch Exception Inside finally Exception in thread "main" java.io.IOException. This question tests your knowledge of Exception Handling in Java. You would need to have a thorough understanding of exception handling to successfully answer this question. (See the note at the end of this answer which gives a brief outline of exception handling). Let's step through the code to see how it runs. ===Code Step Through=== 1: class A { 2: void mA() throws Exception{ 3: try { 4: throw new Exception(); 5: } catch (Exception e) { 6: System.out.println("Inside catch Exception"); 7: throw new java.io.IOException(); 8: } 9: catch (Throwable t) { 10: System.out.println("Inside catch throwable"); 11: } 12: finally{ 13: System.out.println("Inside finally"); 14: }} 15: public static void main(String[] args) throws Exception { 16: A a = new A(); 17: a.mA(); 18: } 19: } On the line 16, a new object of type A is created. On the line 17, a mA() method call is made to the object of type A. =======2======= 1: class A { 2: void mA() throws Exception { 3: try { 4: throw new Exception(); 5: } catch (Exception e) { 6: System.out.println("Inside catch Exception"); 7: throw new java.io.IOException(); 8: } 9: catch (Throwable t) { 10: System.out.println("Inside catch throwable"); 11: } 12: finally{ 13: System.out.println("Inside finally"); 14: } } 15: public static void main(String[] args) throws Exception { 16: A a = new A(); 17: a.mA(); 18: } 19: } On the line 4, inside the method mA(), a new Exception is thrown. =======3======= 1: class A { 2: void mA() throws Exception { 3: try { 4: throw new Exception(); 5: } catch (Exception e) { 6: System.out.println("Inside catch Exception"); 7: throw new java.io.IOException(); 8: } 9: catch (Throwable t) { 10: System.out.println("Inside catch throwable"); 11: } 12: finally{ 13: System.out.println("Inside finally"); 14: } } 15: public static void main(String[] args) throws Exception { 16: A a = new A(); 17: a.mA(); 18: } 19: } The exception, thrown on line 4, is caught by the catch block commencing on the line 5. Inside this catch block, the following is outputted to the screen: "Inside catch Exception" Following on from this, on line 7, a new exception is thrown. This is an IOException which is a checked exception and which is required to be caught. However, as this particular exception is thrown from within a catch block, it is therefore not caught in the code. =======4======= 1: class A { 2: void mA() throws Exception { 3: try { 4: throw new Exception(); 5: } catch (Exception e) { 6: System.out.println("Inside catch Exception"); 7: throw new java.io.IOException(); 8: } 9: catch (Throwable t) { 10: System.out.println("Inside catch throwable"); 11: } 12: finally{ 13: System.out.println("Inside finally"); 14: } } 15: public static void main(String[] args) throws Exception { 16: A a = new A(); 17: a.mA(); 18: } 19: } The programme jumps to line 11 and enters the finally block of code. Inside this block of code on the line 12, the following is printed to the screen: Inside finally The programme then jumps back to the main method to line 18 (the end of the main() method). =======5======= 1: class A { 2: void mA() throws Exception{ 3: try { 4: throw new Exception(); 5: } catch (Exception e) { 6: System.out.println("Inside catch Exception"); 7: throw new java.io.IOException(); 8: } 9: catch (Throwable t) { 10: System.out.println("Inside catch throwable"); 11: } 12: finally{ 13: System.out.println("Inside finally"); 14: }} 15: public static void main(String[] args) throws Exception { 16: A a = new A(); 17: a.mA(); 18: } 19: } As stated, after the execution of the mA() method on the line 17, the programme jumps to the line 18 and following gets printed to the screen: "Exception in thread "main" java.io.IOException" Note: Java Exception Handling An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled. An exception can occur for many different reasons. The following are some scenarios where an exception occurs. ➤ A user has entered an invalid data. ➤ A file that needs to be opened is not be found. ➤ A network connection has been lost in the middle of communications or the JVM has run out of memory. Some of these exceptions are caused by: • User error • Programmer error • Physical resources that have failed in some manner. Based on these, we have three categories of Exceptions. You need to understand them to know how exception handling works in Java. ➤ Checked Exceptions are those exceptions that are checked (notified) by the compiler at compilation-time, these are also called as compile time exceptions. These exceptions cannot simply be ignored, the programmer should take care of (handle) these exceptions. For example: • Exception. • IOException ➤ Unchecked Exception are those exceptions whose handling is NOT verified during Compile time. These exceptions occur because of bad programming. The program won't give a compilation error. All Unchecked exceptions are direct sub classes of RuntimeException class. For example: • IllegalArgumentsException • IndexOutOfBoundsException • IllegalStateException • ArithmeticException • ClassCastException • NullPointerException ➤ Errors are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation. For example: • StackOverflowError • ExceptionInInitializerError • AssertionError • NoClassDefFoundError • OutOfMemoryError

Given: public class B extends A { public void m() { try { throw new Exception(); } catch (Exception e) { System.out.println("In catch"); return; } finally{ System.out.println("finally"); }} public static void main(String[] args){ B b = new B(); b.m(); }} What is the result? (Choose all that apply) a) compiler error b) runtime error c) compile and print In catch and jumps out of m() d) none of the above

d) is correct. The program will be none of the answers suggested. The program will run fine and will print: In catch finally ===Code Step Through=== 1: public class B extends A { 2: public void m() { 3: try { 4: throw new Exception(); 5: } catch (Exception e) { 6: System.out.println("In catch"); 7: return; 8: } 9: finally{ 10: System.out.println("finally"); 11: } 12: } 13: public static void main(String[] args){ 14: B b = new B(); 15: b.m(); 16: }} On the line 14, a new object instance is created of type B. On the line 15, m() method call is made to this particular instance 'b' of type B. =======2======= 1: public class B extends A { 2: public void m() { 3: try { 4: throw new Exception(); 5: } catch (Exception e) { 6: System.out.println("In catch"); 7: return; 8: } 9: finally{ 10: System.out.println("finally"); 11: } 12: } 13: public static void main(String[] args){ 14: B b = new B(); 15: b.m(); 16: }} On the line and 4, inside the method m(), an exception is explicitly thrown. =======3======= 1: public class B extends A { 2: public void m() { 3: try { 4: throw new Exception(); 5: } catch (Exception e) { 6: System.out.println("In catch"); 7: return; 8: } 9: finally{ 10: System.out.println("finally"); 11: } 12: } 13: public static void main(String[] args){ 14: B b = new B(); 15: b.m(); 16: }} The exception that was thrown on the line 4 is caught in the block of code commencing on the line 5. On the line 6, "In catch" is outputted to the screen. =======4======= 1: public class B extends A { 2: public void m() { 3: try { 4: throw new Exception(); 5: } catch (Exception e) { 6: System.out.println("In catch"); 7: return; 8: } 9: finally{ 10: System.out.println("finally"); 11: } 12: } 13: public static void main(String[] args){ 14: B b = new B(); 15: b.m(); 16: }} On the line 7, the 'return' keyword is called which exits the method m(). However, it jumps into the finally block before exiting the method. On the line 9, the 'finally' block gets executed. This is always the case just after the try/catch block completes. The string "finally" gets printed to the screen. Notice the method m() does not have a return type. However, as it is not returning anything, this will compile fine. ======5====== 1: public class B extends A { 2: public void m() { 3: try { 4: throw new Exception(); 5: } catch (Exception e) { 6: System.out.println("In catch"); 7: return; 8: } 9: finally{ 10: System.out.println("finally"); 11: } 12: } 13: public static void main(String[] args) { 14: B b = new B(); 15: b.m(); 16: } } The program then jumps back to the main() method after the execution of the line 15 and the program terminates on the line 16. Final output: In catch finally

Given: int i =0; if (i==0) { System.out.println("01"); continue; if (i==0) { System.out.println("02"); } } else { System.out.println("02"); } What is the result? (Choose all that apply) a) compile and print 01 b) compile and print 02 c) compile and print 03 d) none of the above

d) is correct. The program will give a compiler error int i =0; if (i==0) { System.out.println("01"); continue; if (i==0) { System.out.println("02"); } } else { System.out.println("02"); } Keyword 'continue' can only be used in loops i.e. for or while loop else compile error

Given: public class A { static String s = ""; public static void main(String[] args) { try { s += "1"; m(); } catch (Exception e) { s += "2"; } finally { s += "3"; s += "4"; } System.out.println(s); } static void m() { int x = 0; int y = 7/x; } } What is the result? a) 12 b) 13 c) 123 d) 1234 e) compiler error f) An exception is thrown with no other output

d) is correct. The program will print: 1234. The method m() throws a division by zero exception and this is caught. ===Step Through=== 1: public class A { 2: static String s = ""; 3: public static void main(String[] args) { 4: try { 5: s += "1"; 6: m(); 7: } catch (Exception e) { 8: s += "2"; 9: } 10: finally { 11: s += "3"; s += "4"; 12: } 13: System.out.println(s); 14: } 15: static void m(){ int x = 0; int y = 7/x; } 16: } When this class gets loaded into memory at runtime, the static variable 's' is first initialised on the line 2. Then the static method m() gets initialised on the line 15, followed by the main() method (which is also a static method). Note: If there were non-static initialisation blocks, instance variables or instance methods of the class A, they would be initialised AFTER the static variables, methods and blocks. In the code above, there are none. =======2======= 1: public class A { 2: static String s = ""; 3: public static void main(String[] args) { 4: try { 5: s += "1"; 6: m(); 7: } catch (Exception e) { 8: s += "2"; 9: } 10: finally { 11: s += "3"; s += "4"; 12: } 13: System.out.println(s); 14: } 15: static void m() { int x = 0; int y = 7/x; } 16: } On the line 4, flow control enters the try block of the main method and on the line 5, the string value "1" gets appended to the string s. Snapshot of Current Variables in Memory: s="1" =======3======= 1: public class A { 2: static String s = ""; 3: public static void main(String[] args) { 4: try { 5: s += "1"; 6: m(); 7: } catch (Exception e) { 8: s += "2"; 9: } 10: finally { 11: s += "3"; s += "4"; 12: } 13: System.out.println(s); 14: } 15: static void m(){ int x = 0; int y = 7/x; } 16: } On the line 6, static method m() gets called. On the line 15, program flow enters the static method body of m(). =======4======= 1: public class A { 2: static String s = ""; 3: public static void main(String[] args) { 4: try { 5: s += "1"; 6: m(); 7: } catch (Exception e) { 8: s += "2"; 9: } 10: finally { 11: s += "3"; s += "4"; 12: } 13: System.out.println(s); 14: } 15: static void m(){ int x = 0; int y = 7/x; } 🠅 16: } On the line 15, inside the method m(), there is an attempt to divide by 0. This throws an java.lang.ArithmeticException: / by zero. As there is no try/catch block to catch exceptions inside the method m(), program flow control returns to the main method. =======5======== 1: public class A { 2: static String s = ""; 3: public static void main(String[] args) { 4: try { 5: s += "1"; 6: m(); 7: } catch (Exception e) { 🠄 8: s += "2"; 9: } 10: finally { 11: s += "3"; s += "4"; 12: } 13: System.out.println(s); 14: } 15: static void m(){ int x = 0; int y = 7/x; } 🠅 16: } On the line 15, the arithmetic exception is thrown and is caught on the line 7 of the main method. As a consequence, program flow jumps into the catch block on the line 7. On the line 8, inside the catch block, the string s has "2" appended to it. See memory snapshot below: Snapshot of Current Variables in Memory: s = "2" =======6======= 1: public class A { 2: static String s = ""; 3: public static void main(String[] args) { 4: try { 5: s += "1"; 6: m(); 7: } catch (Exception e) { 8: s += "2"; 9: } 10: finally { 11: s += "3"; s += "4"; 12: } 13: System.out.println(s); 14: } 15: static void m() { int x = 0; int y = 7/x; } 16: } On the line 10, after the catch block completes, flow control enters the finally block. Inside the finally block, string "3" is appended to string s followed by "4" appended to string s. See memory snapshot below with the two new strings appended: Snapshot of Current Variables in Memory: s = "1234" =======7======= 1: public class A { 2: static String s = ""; 3: public static void main(String[] args) { 4: try { 5: s += "1"; 6: m(); 7: } catch (Exception e) { 8: s += "2"; 9: } 10: finally { 11: s += "3"; s += "4"; 12: } 13: System.out.println(s); 14: } 15: static void m() { int x = 0; int y = 7/x; } 16: } On the line 13, after the finally block completes, flow control prints the contents of string s to the screen then code completes: 1234

Given: public class B extends A { static int k = 0; static { k=10/0; } public static void main(String[] args){ B b = new B(); }} What is the result? (Choose all that apply) a) StackOverflowError b) IOException c) AssertionError d) ExceptionInInitializerError

d) is correct. The program will throw an 'ExceptionInInitializerError'. Looking at the program below 1: public class B extends A { 2: static int k = 0; 3: static { 4: k=10/0; 5: } 6: public static void main(String[] args){ 7: B b = new B(); 8: }} On the line 4, within the static initialization block, there is division by zero. The compiler throws an ExceptionInInitializerError which was caused by the ArithmeticException (i.e. division by zero) in the static in in initialization block.

Given: public class Blocker { static String s = ""; public static void main(String[] args) { try { s += "1"; } catch (Exception e) { s += "2"; } finally { s += "3"; s += "4"; m(); } System.out.println(s); } static void m() { int x = 0; int y = 7/x; } } What is the result? a) 12 b) 13 c) 123 d) 1234 e) compiler error f) An exception is thrown with no other output

f) is correct. An exception is thrown with no other output. An ArithmeticException is thrown in the finally block and as a consequence, the finally block does not complete. ===Step Through=== 1: public class Blocker { 2: static String s = ""; 3: public static void main(String[] args) { 4: try { 5: s += "1"; 6: } catch (Exception e) { 7: s += "2"; 8: } 9: finally { 10: s += "3"; s += "4"; 11: m(); 12: } 13: System.out.println(s); 14: } 15: static void m() { int x = 0; int y = 7/x; } 16: } On the line 4, flow control enters the try block and the string value "1" gets appended to the string s. ============== Snapshot of Current Variables in Memory: s = "1" =======2======= 1: public class Blocker { 2: static String s = ""; 3: public static void main(String[] args) { 4: try { 5: s += "1"; 6: } catch (Exception e) { 7: s += "2"; 8: } 9: finally { 10: s += "3"; s += "4"; 11: m(); 12: } 13: System.out.println(s); 14: } 15: static void m() { int x = 0; int y = 7/x; } 16: } As there are no exceptions thrown in try block, the catch block gets skipped and flow control enters the finally block on the line 9. On the line 10, inside the finally block, "3" is appended to string s, then "4" appended to string s. ============== Snapshot of Current Variables in Memory: s = "134" =======3======= 1: public class Blocker { 2: static String s = ""; 3: public static void main(String[] args) { 4: try { 5: s += "1"; 6: } catch (Exception e) { 7: s += "2"; 8: } 9: finally { 10: s += "3"; s += "4"; 11: m(); 12: } 13: System.out.println(s); 14: } 15: static void m() { int x = 0; int y = 7/x; } 16: } On the line 11, the static method m() gets called next. On the line 15, flow control moves to m() and inside this method body there is an attempt to divide by 0. This throws an "java.lang.ArithmeticException: / by zero" The finally block fails to complete and the code throws the ArithmeticException with no other output.


Set pelajaran terkait

CHAPTER 2 PROPERTY REVIEW QUESTIONS

View Set

Exam 2 Questions from Back of the Book

View Set

Chapter 18 Anxiety and Panic Disorder

View Set

Banking System and Financial Services

View Set

CH 23 - fluid/electrolyte imbalance

View Set