OCA Java 7 - VI Flow Control and Exceptions

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

Which one is not legal? 1. try { //do stuff } catch (SomeException ex) { ... } finally { //clean up } 2. try { //do stuff } finally { //clean up } 3. try { //do stuff } catch (SomeException ex) { ... } 4. try { //do stuff }

*4. is illegal* Finally is not required. But you must have either catch or finally after try. Otherwise it will cause compiler error

What is the output of the following code snippet? int x1 = 50, x2 = 75; boolean b = x1 >= x2; if(b = true) System.out.println("Success"); else System.out.println("Failure"); A. Success B. Failure C. The code will not compile because of line 4. D. The code will not compile because of line 5.

*A*. *The code compiles successfully,* so options C and D are incorrect. The value of b after line 4 is false. However, the if-then statement on line 5 contains an assignment, not a comparison. The variable b is assigned true on line 3, and the assignment operator returns true, so line 5 executes and displays Success, *so the answer is option A.*

What does the output of the following contain? (Choose all that apply) 12: public static void main(String[] args) { 13: System.out.print("a"); 14: try { 15: System.out.print("b"); 16: throw new IllegalArgumentException(); 17: } catch (IllegalArgumentException e) { 18: System.out.print("c"); 19: throw new RuntimeException("1"); 20: } catch (RuntimeException e) { 21: System.out.print("d"); 22: throw new RuntimeException("2"); 23: } finally { 24: System.out.print("e"); 25: throw new RuntimeException("3"); 26: } 27: } A. abce B. abde C. An exception with the message set to "1" D. An exception with the message set to "2" E. An exception with the message set to "3" F. Nothing; the code does not compile.

*A, E.* The code begins normally and prints a on line 13, followed by b on line 15. On line 16, it throws an exception that's caught on line 17. Remember, only the most specific matching catch is run. Line 18 prints c, and then line 19 throws another exception. Regardless, the finally block runs, printing e. Since the finally block also throws an exception, that's the one printed.

What is the output of the following code? public class TernaryTester { public static void main(String[] args) { int x = 5; System.out.println(x > 2 ? x < 4 ? 10 : 8 : 7); }}

*Answer is 8* As you learned in the section "Ternary Operator," although parentheses are not required, they do greatly increase code readability, such as the following equivalent statement: System.out.println((x > 2) ? ((x < 4) ? 10 : 8) : 7) We apply the outside ternary operator first, as it is possible the inner ternary expression may never be evaluated. Since (x>2) is true, this reduces the problem to: System.out.println((x < 4) ? 10 : 8) Since x is greater than 2, the answer is 8

What is the result of the following code snippet? final char a = 'A', d = 'D'; char grade = 'B'; switch(grade) { case a: case 'B': System.out.print("great"); case 'C': System.out.print("good"); break; case d: case 'F': System.out.print("not good"); } A. great B. greatgood C. The code will not compile because of line 3. D. The code will not compile because of line 6. E. The code will not compile because of lines 6 and 9.

*B.* The code compiles and runs without issue, so options C, D, and E are not correct. The value of grade is 'B' and there is a matching case statement that will cause "great" to be printed. There is no break statement after the case, though, so the next case statement will be reached, and "good" will be printed. There is a break after this case statement, though, so the switch statement will end. The correct answer is thus option B.

What is the output of the following code snippet? do { int y = 1; System.out.print(y++ + " "); } while(y <= 10); A. 1 2 3 4 5 6 7 8 9 B. 1 2 3 4 5 6 7 8 9 10 C. 1 2 3 4 5 6 7 8 9 10 11 D. The code will not compile because of line 6. E. The code contains an infinite loop and does not terminate

*D*. The variable y is declared within the body of the do statement, so *it is out of scope* on line 6. Line 6 generates a compiler error, so option D is the correct answer.

What is the output of the following code snippet? int x = 1, y = 15; while x < 10 y--; x++; System.out.println(x+", "+y); A. 10, 5 B. 10, 6 C. 11, 5 D. The code will not compile because of line 3. E. The code will not compile because of line 4. F. The code contains an infinite loop and does not terminate.

*E.* This is actually a much simpler problem than it appears to be. The while statement on *line 4 is missing parentheses*, so the code will not compile, and option E is the correct answer. If the parentheses were added, though, option F would be the correct answer since the loop does not use curly braces to include x++ and the boolean expression never changes. Finally, if curly braces were added around both expressions, the output would be 10, 6 and option B would be correct.

List the errors

*ExceptionInInitializerError* Thrown by the JVM when a static initializer throws an exception and doesn't handle it *StackOverflowError* Thrown by the JVM when a method calls itself too many times (this is called infnite recursion because the method typically calls itself without end) *NoClassDefFoundError* Thrown by the JVM when a class that the code uses is available at compile time but not runtime

List the checked exceptions

*FileNotFoundException* Thrown programmatically when code tries to reference a fle that does not exist *IOException* Thrown programmatically when there's a problem reading or writing a fle

Will this code compile? And if yes, what is the output? int x = 20; while(x>0) { do { x -= 2 } while (x>5); x--; System.out.print(x+"\t"); }

*It will compile and output* *3 0* The first time this loop executes, the inner loop repeats until the value of x is 4. The value will then be decremented to 3 and that will be the output at the end of the first iteration of the outer loop. On the second iteration of the outer loop, the inner do-while will be executed once, even though x is already not greater than 5. As you may recall, do-while statements always execute the body at least once. This will reduce the value to 1, which will be further lowered by the decrement operator in the outer loop to 0. Once the value reaches 0, the outer loop will terminate. The result is that the code will output the following:3 0

Will this compile and if yes, what will be the output? Object o = null; System.out.println(o)

*It will print null* and will not throw a NullPointerException. Because if print/println methods get null as input parameter, they print "null". They do not try to call toString() on null.

What is the problem with this code (If anything) public class Parser{ public static void main( String[] args){ try{ int i = 0; i = Integer.parseInt( args[0] ); } catch(NumberFormatException e){ System.out.println("Problem in " + i ); } } }

*It won't compile* Because 'i' is defined in try block and so it is not visible in the catch block.

What's the problem with this code (if anything) public class TestClass{ public static void main(String args[]) { int x = Integer.parseInt(args[0]); switch(x){ case x < 5 : System.out.println("BIG"); break; case x > 5 : System.out.println("SMALL"); default : System.out.println("CORRECT"); break; } } }

*It won't compile* Because the type of the case labels must be consistent with the type of the switch condition. Here, switch condition is an int, so the case label values must be assignable to the switch condition variable. The expression x<5 is of type boolean, which cannot be assigned it x (since it is an int).

What's wrong with this code? (If anything) for(int k; k<0; k++ )

*It won't compile* You need to initialize k first. It'll work this way for(int k=0; k<0; k++)

What is the problem with this code? (if any) while (int x == 2 ) { //do stuff }

*It's illegal and won't compile* Any variables used in the expression of a while loop must be declared before the expression is evaluated

What are the last two things that happens in for loop?

*Iteration expression* and then *conditional expression* are always the last two things that happens in for loop (Except for forced exit)

Will this code compile, and if not, why? byte g = 2; switch (g) { case 23: ... ; case 128: ... ; }

*No* Although the switch argument is legal, a byte is implicitly cast to int, the second case argument (128) is too big for a byte, and compiler knows it. Test. java:4 possible loss of precision fount :int required :byte case :128

Can we throw an exception in catch block and handle it in another catch block from the same level?

*No* Exception thrown by a catch cannot be caught by the following catch blocks at the same level.

Does switch's default case have to come at the end of switch?

*No* It can be located at any place inside switch

Will this compile? int x = 0; for(long y = 0, x = 4; x < 5 && y < 10; x++, y++) { System.out.print(x + " "); }

*No* It does not compile because of the initialization block. The reason is that x is repeated in the initialization block after already being declared before the loop, resulting in the compiler stopping because of a duplicate variable declaration. We can fix this loop by changing the declaration of x and y as follows: int x = 0; long y = 10; for(y = 0, x = 4; x < 5 && y < 10; x++, y++) { System.out.print(x + " "); }

Is it valid? for (int i=5; i=0; i--) { }

*No* It uses '=' instead of '==' for condition which is invalid. The loop condition must be of type boolean.

Is it valid? int j=5; for(int i=0, j+=5; i<j ; i++) { j--; }

*No* It uses 'j +=5'. Now, this statement is preceded by 'int i=0,' and that means we are trying to declare variable j. But it is already declared before the for loop. If we remove the int in the initialization part and declare i before the loop then it will work. But if we remove the statement int j = 5; it will not work because compiler will try to do j = j+5 and you can't use the variable before it is initialized. Although the compiler gives a message 'Invalid declaration' for j += 5 but it really means the above mentioned thing.

Does basic for loop's *iteration expression* necessarily have to increment something?

*No* It's not increment expression. It's iteration expression. You can put there any code that you want to be executed with each iteration

Can static or initialization block throw Checked Exception?

*No* Static or instance initializer can only throw a RuntimeException. If you try to throw a checked exception from a static or instance initializer block to the outside, the code will not compile.

Can method throw *multiple exceptions* to it's caller?

*No* The Exception that is thrown in the last, is the Exception that is thrown by the method to the caller. Other exceptions thrown by the code prior to this point are lost.

Is it possible? while ( ) break ;

*No* The condition expression in a while header is required.

Can we use variable *declared* (not just initialized) within the basic for loop declaration outside the for loop?

*No* They can't be accessed outside the loop. They are block scope variables

Can we use a number or anything that does not evaluate to a boolean value as a condition for an if statement or looping construct?

*No* You can't, for example, say if(x), unless x is a boolean

Will this compile and run? class Game{ public void play() throws Exception{ //some code; } } public class Soccer extends Game{ public void play(){ //some code; } public static void main(String[] args){ Game g = new Soccer(); g.play(); } }

*No. It won't compile* Observe that play() in Game declares Exception in its throws clause. Further, class Soccer overrides the play() method without any throws clause. This is valid because a list of no exception is a valid subset of a list of exceptions thrown by the superclass method. Now, even though the actual object referred to by 'g' is of class Soccer, the class of the variable g is of class Game. Therefore, at compile time, *compiler assumes that g.play() might throw an exception*, because Game's play method declares it, and thus expects this call to be either wrapped in a try-catch or the main method to have a throws clause for the main() method.

Which parts of the basic for loop declaration is mandatory and which ones we can miss?

*None of three parts* of the basic for loop declaration is required. The following code is perfectly legal and results in endless loop for ( ; ; ) { //do stuff } With the *absence of the initialization and increment sections* , the loop will act like a while loop int i = 0; for ( ; i < 10 ; ) { //do stuff }

Will following code snippet compile? And if yes, what is the output of it? boolean x = true, z = true; int y = 20; x = (y != 10) ^ (z=false); System.out.println(x+", "+y+", "+z);

*The code compiles and runs without an issue.* This example is tricky because of the second assignment operator. The expression (z=false) assigns the value false to z and returns false for the entire expression. Since y does not equal 10, the left-hand side returns true; therefore, the exclusive or (^) of the entire expression assigned to x is true. The output reflects these assignments, with no change to y, so the answer is *true, 20, false*.

Which of these case statements won't compile and why? private int getSortOrder(String firstName, final String lastName) { String middleName = "Patricia"; final String suffix = "JR"; int id = 0; switch(firstName) { case "Test": return 52; case middleName: id = 5; break; case suffix: id = 0; break; case lastName: id = 8; break; case 5: id = 7; break; case 'J': id = 10; break; case java.time.DayOfWeek.SUNDAY: id=15; break; } return id; }

*The first case statement* compiles without issue using a String literal and is a good example of how a return statement, like a break statement, can be used to exit the switch statement early. *The second case statement* does not compile because middleName is not a final variable, despite having a known value at this particular line of execution. *The third case statement* compiles without issue because suffix is a final constant variable. *The fourth case statement*, despite lastName being final, it is not constant as it is passed to the function; therefore, this line does not compile as well. Finally, the *last three case statements* don't compile because none of them have a matching type of String; the last one is an enum value.

Will this compile? int x = 0; for(long y = 0, z = 4; x < 5 && y < 10; x++, y++) { System.out.print(y + " "); } System.out.print(x);

*This code will compile and print the following when executed:* *0 1 2 3 4* First, you can declare a variable, such as x in this example, before the loop begins and use it after it completes. Second, your initialization block, boolean expression, and update statements can include extra variables that may not reference each other. For example, z is defined the initialization block and is never used. Finally, the update statement can modify multiple variables.

Will this code compile? If yes, what is the output? int total = 0; int[] countsOfMoose = new int[3]; for (int i = 0; i <= countsOfMoose.length; i++) total += countsOfMoose[i];

*Yes it compiles.* *But it throws an exception at runtime.* The problem is that the for loop should've have *<* instead of *<=*. On the fnal iteration of the loop, Java tries to call countsOfMoose[3], which is invalid. The array includes only three elements, making 2 the largest possible index. The output looks like this: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3

Can runtime exception be given in a throw clause?

*Yes* Any exception can be given in throw clause

Can we omit curly braces in *basic for loop* declaration.

*Yes* But only if you have single statement inside for block. for (int i = 0; i < size; i++) a += b; Is the same as for (int i = 0; i < size; i++) { a += b; }

Can we handle errors?

*Yes* But we *usually don't*. Because there's not much that we can do about that

Can overriding method might not declare any throws clause if the original method has a throws clause?

*Yes* No exception (i.e. an empty set of exceptions) is a valid subset of the set of exceptions thrown by the original method so an overriding method can choose to not have any throws clause.

Can we initialize more than one variable in the first part of for loop declaration?

*Yes* They must be the same type and separated by comma

Can we create our own exception?

*Yes* They will be considered as checked exceptions (unless you're extending Runtime Exception) and the compiler will enforce the handle or declare rule for that exception

Is it possible? switch (1) { default : break; }

*Yes* You can use a constant in switch(...);

Can we catch more than one exception with single catch clause?'

*Yes* If the exception class that you specified in the catch clause has no subclasses, then only the specified class of exception will be caught . However, if the class specified in catch does have subclasses, any exception object that subclasses it will be caught as well

Can we use primitive wrapper classes in switch's expression?

*Yes* This code is legal switch (new Integer(4)) { case 4: System.out.println("boxing is OK"); }

When does *ArithmeticException* occur?

*java.lang.ArithmeticException extends java.lang.RuntimeException* Thrown when you try to divide by zero. Example : public class X { int k = 0; public static void main(String[] args){ k = 10/0; //throws java.lang.ArithmeticException } }

When does *ArrayIndexOutOfBoundsException* occur?

*java.lang.ArrayIndexOutOfBoundsException extends java.lang.RuntimeException* Thrown when attempting to access an array with an invalid index value (either negative or beyond the length of the array). Example : int[] ia = new int[]{ 1, 2, 3}; // ia is of length 3. System.out.println(ia[3]); //exception !!!

When does *AssertionError* occur?

*java.lang.AssertionError extends java.lang.Error* Thrown to indicate that an assertion has failed i.e.when an assert statement's boolean test expression returns false. Note that the programmer does not explicitly throw AssertionError using the throw keyword. The JVM throws it automatically when an assertion fails. Example: private void internalMethod(int position) { assert (position<100 && position >0) : position; //throws AssertionError if position is < 100 and > 0 }

When does *ClassCastException* occur?

*java.lang.ClassCastException extends java.lang.RuntimeException* Thrown when attempting to cast a reference variable to a type that fails the IS-A test. Example : Object s = "asdf"; StringBuffer sb = (StringBuffer) s; //exception at runtime because s is referring to a String.

When does programmatical *IllegalArgumentException* occurs?

*java.lang.IllegalArgumentException extends RuntimeException* Thrown when a method receives an argument that the programmer has determined is not legal. Example: public void processData(byte[] data, int datatype) { if(datatype != 1 || datatype != 2) throw new IllegalArgumentException(); else ... }

When does *NullPointerException* occur?

*java.lang.NullPointerException extends java.lang.RuntimeException* Thrown when attempting to call a method or field using a reference variable that is pointing to null. Example : String s = null; System.out.println(s.length()); //NullPointerException at runtime because s is null.

When does programmatical *NumberFormatException* occur?

*java.lang.NumberFormatException extends java.lang.IllegalArgumentException* It is thrown when a method that converts a String to a number receives a String that it cannot convert. Example: Integer.parseInt("asdf");

When does programmatical *SecurityException* occur?

*java.lang.SecurityException extends java.lang.RuntimeException* Thrown if the Security Manager does not permit the operation performed due to restrictions placed by the JVM. For example, when a java program runs in a sandbox (such as an applet) and it tries to use prohibited APIs such as File I/O, the security manager throws this exception. Since this exception is explicitly thrown using the new keyword by a security manager class, it can be considered to be thrown by application programmer.

When does *StackOverflowError* occur?

*java.lang.StackOverflowError extends java.lang.Error* Thrown when the stack is full. Usually thrown when a method calls itself and there is no boundary condition. Example : public void m1(int k){ m1(k++); // exception at runtime. }

What method of Throwable class will print stack from where the exception occurred?

*printStackTrace();* It will print the most recently entered method first and continue down printing the name of each method as it works it's way down the call stack (this is called unwinding the stack) from the top

*Checked exceptions* you need to know about for exam are ...

... 1. *java.io.IOException* extends java.lang.Exception, 2. *java.io.FileNotFoundException* extends java.io.IOException.

Switch statement's case constant must be ...

... *compile-time final variable* or a constant expression , including enum or a String

Any exception thrown in a static block is wrapped into...

... ExceptionInInitializerError

Both Error and Exception derives from ...

... Throwable

All subtypes of *Exception*, excluding *RuntimeException* and it's subtypes, are ...

... checked exceptions

If a condition in a switch statement matches a case constant, ...

... execution will run through all code in the switch following the matching case statement until a break statement or the end of the switch statement is encountered. In other words, the matching case *is just an entry point into the case block*, but unless there's a break statement, the matching case isn't the only case code that runs

An unlabeled *break* statement will cause ...

... the current iteration of the innermost looping construct to stop and the line of code following the loop to run

An unlabeled continue statement will cause ...

... the current iteration of the innermost looping construct to stop, the condition of that loop to be checked and if the condition is met, the loop to run again

Describe these exceptions and answer who throws them? 1. ArrayIndexOutOfBounds exception 2. ClassCastException 3. IllegalArgumentException 4. IllegalStateException 5. NullPointerException 6. NumberFormatException 7. AsertionError 8. ExceptionInInitializerError 9. StackOverflowError 10. NoClassFoundError 11. ArithmeticException 12. SecurityException

1. *ArrayIndexOutOfBounds exception* - Thrown when attempting to access an array with an invalid index value (either negative or beyond the length of the array). By the JVM 2. *ClassCastException* Thrown when attempting to cast a reference variable to a type that fails the IS-A test. By the JVM 3.*IllegalArgumentException* Thrown when a method receives an argument formatted differently than the method expects. Thrown Programmatically 4. *IllegalStateException* Thrown when the state of the environment doesn't match the operation being attempted—for example, using a scanner that's been closed. Programmatically 5. *NullPointerException* Thrown when attempting to invoke a method on, or access a property from, a reference variable whose current value is null. By the JVM 6. *NumberFormatException* Thrown when a method that converts a String to a number receives a String that it cannot convert. Programmatically 7. *AssertionError* Thrown when an assert statement's boolean test returns false. by JVM 8. *ExceptionInInitializerError* When we have any exception throwned in static initialization block, it's wrapped into ExceptionInInitializerError and throwned out as this. By the JVM 9. *StackOverflowError* Typically thrown when a method recurses too deeply. (Each invocation is added to the stack.) When the stack is full. Usually thrown when a method calls itself and there is no boundary condition. By the JVM 10. *NoClassDefFoundError * Thr*own when the JVM can't find a class it needs, because of a command line error, a classpath issue, or a missing .class file. By the JVM 11. *ArithmeticException* Thrown when you try to divide by zero. By the JVM. 12. *SecurityException* Thrown if the Security Manager does not permit the operation performed due to restrictions placed by the JVM. Thrown Programmatically.

1. Why to use break and continue? 2. Where to use break and continue?

1. *Break* - we use it to stop entire loop *Continue* - we use it to stop current iteration 2. *Break* - we can use it in switch statement and loops *Continue* - we can use it only inside a loop

Which two categories of exceptions do we have? (except for Runtime/non Runtime)

1. *JVM Exceptions* Those exceptions or errors that are either exclusively or most logically thrown by the JVM 2. *Programmatic Exceptions* Those exceptions that are thrown explicitly by application and/or API programmers

1. Can we have any code in between catch blocks? 2. If an exception occurred on line 3 of the try block, would the rest of the code in try block be executed?

1. *No* We can't have any code in between catch blocks 2. *No* The rest of the code will never be executed. Once control jumps to the catch block, it will never get back to try block

How we can achieve *forced exit* from a loop?

1. *break* Execution jumps immediately to the first statement after the for loop 2. *return* Execution jumps immediately back to the calling method 3. *System.exit();* All program execution stops. The JVM shuts down 4. *Throw an Exception*

1. Syntax of enhanced for loop 2. Describe each element

1. *for (declaration:expression)* 2. *declaration* - the newly declared block variable. of a type compatible with the elements of the array you accessing. This variable will be available within the for block and it's value will be the same as the current Collection element *expression* - this must evaluate to the array (or a Collection) you want to test through. This could be an array variable or a method call that returns an array.

What we are allowed to specify as a condition in if statement?

1. Boolean expression 2. Something that resolves to boolean 3. Boolean reference

Exceptions come in two flavors ...

1. Checked 2. Uncecked

1. How do we commonly refer to if and switch statements? 2. What is their purpose?

1. Decision statements 2. They are asking the program to evaluate a given expression to determine which of predetermined code blocks to run (which course of action to take)

A basic for statement has three parts:

1. Declaration/initialization int i = 0; 2. Boolean evaluation i > 0; 3. Iteration expression i++;

1. How many and which parts does enhanced loop declaration have? 2. Why to use it?

1. It has two parts - *Declaration* - block variable, whose type is compatible with the elements of the array or collection, and it contains the value of the element for given iteration - *Expression* - array or collection through which you want to loop 2. We use it to *loop through arrays or collections*

What are the rules for "default" keyword in switch statement?

1. The default keyword should be used in a switch statement if you want to run some code if none of the key values match the conditional value 2. The default keyword can be located anywhere in the switch block (but convention is to place it in the bottom)

Which types of loops we have in Java?

1. While - we use it when we don't know how many times a block or statement should repeat 2. Do - expression isn't evaluated until after the do loop's code executed once. The code is guarantied to run at least once. 3. For - we use it when we know how many times a block or statement should repeat. We have basic and enhanced for loop (to loop through array or Collection, when you know number of iterations)

1. How many variables you can declare in declaration/initialization part of basic "for" loop declaration? 2. When does declaration/initialization happens?

1. You can declare *from zero to many variables* inside the parentheses after for keyword, as long as they are *from the same type and separated by commas* for (int x=10,y=3; y>3; y++) { ... } 2. Declaration/initialization *happens the first thing in the loop* and whereas the other two parts - the boolean test and iteration expression - will run with each iteration of loop, the declaration and initialization happens just once, at the very beginning. The scope of variables declared in for loop ends with the for loop.

Rules for using *else* and *else-if* are...

1. You can have zero or one "else" for a give "if", and it must come after any "else if"s 2. You can have zero to many "else-if"s for a given "if" and they must come before the "else" 3. Once an "else if" succeeds, none of the remaining "else if"s nor the "else" will be tested

1. Syntax of "if" statement 2. What is optional in "if" statement?

1. if (boolean expression) { statements; } else { statements; } 2. - The "else" block is optional - "else if" blocks are optional - curly braces are optional if you have only one statement to execute within body of the conditional block. (It's good practice to always include curly braces) - if there's else, it should be at the bottom after all "else-if"s

1. General syntax of switch statement? 2. What switch's expression can evaluate to? 3. What case constant can and must evaluate to?

1. switch (expression) { case constant 1: code block; case constant 2: code block; case constant 3: code block; } 2. A switch's expression can evaluate to an char, byte, short, int, String, enum 3. A case constant must evaluate to the some type that the switch expression can use with one big constraint - The case constant must be a compile-time constant! You can use only a constant or a final variable that is immediately initialized with a literal value. It's not enough to be a final. it must be compile-time final. final int a = 1; final int b; b = 1; int x = 0; switch (0) { case a: //OK case b: //Compiler error } Also switch can check only for equality, no other relational operators, such as > or < allowed

What is printed when you use exception.printStackTrace()?

A complete chain of the names of the methods called, along with the line numbers, is printed. It contains the names of the methods in the chain of method calls that led to the place where the exception was created

What is the main feature of try/catch block's *finally block*? Why to use it?

A finally block encloses code that is always executed at some point after the try block, whether an exception was thrown or not. Even if there is a return statement in the try block, the finally block executes right after the return statement is encountered and before the return executes. This is the right place to close your files, release your network sockets, and perform any other cleanup your code requires. If the try block executes with no exceptions, the finally block is executed immediately after the try block completes. If there was an exception thrown, the finally block executes immediately after the proper catch block completes.

What is printed when you use System.out.println(exception)?

A stack trace is not printed. Just the name of the exception class and the message is printed.

How should we order catch blocks if we have multiple number of them in one try/catch block?

All catch blocks must be ordered *from most specific to most general*. If you have a catch clause for both IOException and Exception, you must put the catch for IOException first in your code. Otherwise, the IOException would be caught by catch(Exception e), because a catch argument can catch the specified exception or any of its subtypes! The compiler will stop you from defining catch clauses that can never be reached.

What happens if you have an exception and you never catch it?

An exception that's *never been caught*, will cause application stop running

Handle or declare rule

Any method that might throw checked exception (including methods, that invoke a methods that can throw a checked exception) must either declare the exception using throw keyword or handle it using try/catch block

List the unchecked exceptions

ArithmeticException Thrown by the JVM when code attempts to divide by zero ArrayIndexOutOfBoundsException Thrown by the JVM when code uses an illegal index to access an array ClassCastException Thrown by the JVM when an attempt is made to cast an exception to a subclass of which it is not an instance IllegalArgumentException Thrown by the programmer to indicate that a method has been passed an illegal or inappropriate argument NullPointerException Thrown by the JVM when there is a null reference where an object is required NumberFormatException Thrown by the programmer when an attempt is made to convert a string to a numeric type but the string doesn't have an appropriate format

What condition do errors, exceptions and runtime exceptions represent?

Exception and Error derives from Throwable. 1.*Error* represents unusual situations that are not caused by program errors, and indicate things that would not normally happen during program execution, such as JVM running out of memory. Generally your application would not be able to recover from and Error therefore you are not required to handle them. (You can if you want, though) 2. *Exception* represents something that happens not as a result of a programming error, but rather because some resource is not available or some other condition required for correct execution is not present. For example, if your application is supposed to communicate with another application or computer that is not answering, this is an exception that is not caused by a bug. 3. *Runtime Exceptions* - are a special case because they sometimes do indicate program errors. They can also represent rare, difficult-to-handle exceptional conditions.

How many times will the following code print "Hello World"? 3: for(int i=0; i<10 ; ) { 4: i = i++; 5: System.out.println("Hello World"); 6: } A. 9 B. 10 C. 11 D. The code will not compile because of line 3. E. The code will not compile because of line 5. F. The code contains an infinite loop and does not terminate.

F. In this example, the update statement of the for loop is missing, which is fine as the statement is optional, so option D is incorrect. The expression inside the loop increments i but then assigns i the old value. Therefore, i ends the loop with the same value that it starts with: 0. The loop will repeat infinitely, outputting the same statement over and over again because i remains 0 after every iteration of the loop.

What does *ducking* mean?

If a method doesn't provide a catch clause for a particular exception, that method is said to be *"ducking"* the exception (or "passing the buck")

What is the problem with this code? public void doStuff() { try { //risky IO things } catch(IOException ex) { //can't handle it throw ex; } }

If you throw a checked exception from a catch clause, you must also declare that exception. In other words, you must *handle AND declare* as opposed to *handle OR declare*. The example is illegal. If you wanna re-throw the IOException you must declare it.

What is difference in rules for exceptions while overriding and exceptions while extending a class which constructor throws an exception(s)?

In overriding, you can throw less or narrower(subclass) checked exceptions. But in extending (while superclass' constructor throwing exception) you can throw more or broader(superclass) checked exceptions. If the subclass constructor's throws clause includes the same exception or its superclass, then it can throw any other exception as well.

If there're multiple if's and only one else, to which if it belongs to?

It belongs *to the innermost if statement to which it might possibly belong* (in other words, the closest preceding if that doesn't have an else)

What does *unchecked* means and what we can mark unchecked?

It means that compiler doesn't enforce the *handle or declare rule* on it. You're free to handle these exceptions/error or to declare them, but compiler doesn't care. Subtypes of Error and RuntimeException are unchecked

What will happen if you use conditional *finally block* in try/catch statement?

It will always be invoked, *regardless* of whether an exception in the corresponding try is thrown or not, and regardless of whether a thrown exception is caught or not

What is the only exception to the finally-will-always-be-called rule?

It will happen only if JVM shuts down. That could happen if code from the try/catch block *calls System.exit();* Code in finally also can itself raise an exception or issue a System.exit();

What will this code print? (if anything) public class FinallyTest{ public static void main(String args[]) throws Exception{ try{ m1(); System.out.println("A"); } finally{ System.out.println("B"); } System.out.println("C"); } public static void m1() throws Exception { throw new Exception(); } }

It will print B and throw Exception. Remember, finally always runs

What is the purpose of exception handling?

It's Java's mechanism for handling errors that produces efficient and organized error-handling code

When does basic for loop *iteration* run?

Iteration always happens *after the loop body runs.* Declaration/initialization runs first in the loop. Then conditional test runs. Then, if test is true, loop body runs. Then incremention expression runs

Where should we place label statement?

Just before the statement being labeled foo: for (int x = 0; x < 10; x++) { while (y>7) { y--; } }

What is the result of this code? 26: try { 27: throw new RuntimeException(); 28: } catch (RuntimeException e) { 29: throw new RuntimeException(); 30: } finally { 31: throw new Exception(); 32: }

Line 27 throws an exception, which is caught on line 28. The catch block then throws an exception on line 29. If there were no finally block, the exception from line 29 would be thrown. However, the finally block runs after the try block. Since the finally block throws an exception of its own on line 31, this one gets thrown. The exception from the catch block gets forgotten about. This is why you often see another try/catch inside a finally block—to make sure it doesn't mask the exception from the catch block.

Can we have more than one case label using same value?

No

Can we use this in static context?

No

Is *default clause* mandatory in switch clause?

No

Given the code: static void doSomething() { int[] array = new int[4]; array[4] = 4; doSomethingElse(); } Will doSomethingElse() method ever be executed?

No array[4] = 4; causes *ArrayIndexOutOfBoundsException* so execution never gets to doSomethingElse() method

What will following code print? boolean flag = false; if (!flag) System.out.println("One") else System.out.println("Two") ;

One

Can we omit curly braces in if statement?

Only if we have single statement

Will this code compile and run and why? boolean boo = false; if (boo = true) { ... }

The code compiles and runs fine, and the if test succeeds, because boo is set to true. (rather than TESTED for true) in the argument. But only variables that can be assigned (rather than being compared against something else) are a boolean or Boolean. All other assignments will result in something non-boolean, so they're not legal, as in the following: int x = 3; if (x=5) { ... } //Won't compile, because x is not a boolean and expression returns int 5 instead of boolean

What is the key difference in while, for and do loops flow?

The do loop will enter the body of the loop at least once (without checking the condition) even if the test condition isn't met, unlike for and while loops

Why and how do we declare exceptions?

The exceptions that a method can throw must be declared (unless the exceptions are subclasses of RuntimeException). The list of thrown exceptions is part of a method's public interface. void myFunction() throws MyException1, MyException2 { // code for the method here } Any method that might throw an exception (unless it's a subclass of RuntimeException) must declare the exception. That includes methods that aren't actually throwing it directly, but are "ducking" and letting the exception pass down to the next method in the stack. If you "duck" an exception, it is just as if you were the one actually throwing the exception. RuntimeException subclasses are exempt, so the compiler won't check to see if you've declared them. But all non RuntimeExceptions are considered "checked" exceptions, because the compiler checks to be certain you've acknowledged that "bad things could happen here."

Describe 3 rules of switch statement

Three rules must be remembered about switch statement: 1. Only *String, byte, char, short, int, and enum* values can be used as types of a switch variable. (String is allowed since Java 7.) 2. The switch variable must be *big enough* to hold all the case constants. So, if switch variable is of type char, then none of the case constants can be greater than 65535 because char's range is from 0 to 65535. 3. All case labels should be *COMPILE TIME CONSTANTS*. This means you can use only literals, enum constants, or final constant variables of the same data type. By final constant, we mean that the variable must be marked with the final modifier and initialized with a literal value in the same expression in which it is declared.

What is the rule for equality of two Strings when String is evaluated in switch's expression?

Two Strings will be considered "equal" if they have *the same case-sensitive sequence of characters* Legal: String s = "Monday" switch(s) { case "Monday": ... //matches } Illegal: String s = "MONDAY" switch(s) { case "Monday": ... // does NOT match!

What happens with uncaught exceptions?

Uncaught exceptions propagate back through the call stack, starting from the method where the exception is thrown and ending with either the first method that has a corresponding catch for that exception type or a JVM shutdown (which happens if the exception gets to main(), and main() is "ducking" the exception by declaring it).

How do we call the dropping down the list of case specific code blocks in switch statements?

We call it *fall-through* (Because fall-through is less that intuitive, Oracle recommends that you add a comment such as //fall-through when you use fall-through logic)

What is the reason to use labeled break and continue statements?

We use them if we want to implement break or continue effect on chosen loop, not just innermost one

How does exception matching works?

When an exception is thrown, Java will try to find (by looking at the available catch clauses from the top down) a catch clause for the exception type. If it doesn't find one, it will search for a handler for a supertype of the exception. If it does not find a catch clause that matches a supertype for the exception, then the exception is propagated down the call stack

Is empty switch clause a valid expression?

Yes

Basic for loop syntax

for (declaration/initialization; condition; iteration) { /* loop body */ } for (int=0; i<10; i++) { System.out.println("loop"); }

When does programmatical *IllegalStateException* occur?

j*ava.lang.IllegalStateException extends java.lang.RuntimeException* Signals that a method has been invoked at an illegal or inappropriate time. In other words, the Java environment or Java application is not in an appropriate state for the requested operation. Example: Connection c = ...; public void useConnection() { if(c.isClosed()) throw new IllegalStateException(); else ... }

When does *ExceptionInInitializerError* occur?

java.lang.ExceptionInInitializerError extends java.lang.Error Thrown when any exception is thrown while initializing a static variable or a static block. Example : public class X { int k = 0; static { k = 10/0; //throws java.lang.ArithmeticException //but this is wrapped into a //ExceptionInInitializationError and thrown outside. } }

When does *NoClassDefFoundError* occur?

java.lang.NoClassDefFoundError extends Error Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found. The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found. Example : Object o = new com.abc.SomeClassThatIsNotAvailableInClassPathAtRunTime(); // exception at runtime.

Syntax for try/catch block and explain each element

try { //guarded region } catch (myFirstException) { //code that handles exception } catch (mySecondException) { //code that handles exception } Try is used to define block of code in which exceptions may occur. This block of code is called a *"guarded region"* (which really means "risky code goes here"). One or more catch clauses match a specific exception (or group of exceptions) to a block of code that handles it.

What is syntax of *while loop* and when better to use it?

while (expression) { //do stuff } The while loop is good when you *don't know how many times a block or statement should repeat*. The body of while loop will execute only if the expression results in true, Any variables used in while loop's expression must be declared before the expression is evaluated.


संबंधित स्टडी सेट्स

PHY2020 Ch. 15 Homework Questions

View Set

Series 66: Uniform Securities Act (Business Practices)

View Set

Promotion Board Study Guide- U.S Flag Questions

View Set

Module 9 Monitoring for Health Problems

View Set

unit 2 - pituitary adenoma case study quiz

View Set