OCA Chap 6
Finally: Finally always runs
1. 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. 2.right place to close your files, release your network sockets and to do any clean up. 3.Finally clauses are not required. 4.Legal to have only try&finally. 5. Illegal to have try without a catch or finally, compiler error. 6. Illegal to have code between try and catch. 7. Any catch clauses must immediately follow the try block. 8. Any finally clause must immediately follow the last catch clause (or it must immediately follow the try block if there is no catch block).
Basic for loop: Conditional (boolean) expression
1. Can only have one logical expression but it can be very complex. for example: This is legal for (int x=0; (((x<10)&&(y-->2))|x==3));x++{ } This is NOT legal: too many expressions. for (int x = 0; (x>5),(y<2);x++){ }
Break and Fall-through in switch blocks Most important thing to remember about the flow of execution through a switch statement is
1. Case constants are evaluate from the top down and the first case constant that matches the switch's expression is the execution entry point. This means once a case constant is matched the JVM will execute the associated code block and ALL subsequent code blocks (barring a break statement) too! See example next card
Basic for loop 1
1. In for loops if you are declaring more than one variable separate them with commas. Example: for (int x = 10, y = 3; y>3; y++) { } the declaration and initialization part in a "for loop" only runs once while, conditional and iterations runs with each iteration of loop.
Basic for Loop: Iteration Exrpression
1. Iteration always happens after the loop body runs. 2. Keep in mind that barring a forced exit, evaluating the iteration expression and the evaluation the conditional expression are always the last two things that happens in a for loop. 3. example of forced exits are break, a return, a system.exit( ), and an exception which will all cause a loop to terminate abruptly without running the iteration expression.
Rules for using else and else if
1. You can have zero or no else for a given if, and it must come after any else ifs. 2. You can have zero to many else ifs for a given if and they must come before the optional else. 3. Once an else if succeeds, none of the remaining else ifs nor the else will be tested.
1. int y = 5; int x =2; if (((x>3)&&(y<2)) | doStuff( )){ sysout("true"); } 1. int y = 5; int x =2; if ((x>3)&&(y<2) | doStuff ( )){ sysout ("true"); } Assuming in both cases doStuff( ) is true. What is the output in each case?
1. true 2. prints nothing In some language 0 == false and 1==true. NOT in java
Catching an Exception using try and catch
1. when an exception is thrown the exception handler catches the thrown exception. 2. Try block defines which exceptions may occur. 3. A catch block must immediately follow the try block. If you have one or more catch blocks, they must immediately follow the try block 4. The catch blocks must all follow each other without any other statements or blocks in between. Order in which the catch blocks appears matters.
Legal and Illegal loop expressions int x = 1; 1. while (x) { } 2. while (x=5) { } 3. while (x==5) { } 4. while (true) { }
1. wont compile x is not boolean. 2. resolves to 5, wont compile 3. legal, equality test 4. legal
For loops
2 Structures: Old style is basic and new one is enhanced for loop or for each or for in the for loop is used when you know how many tumes you need to execute the statements in the loop's block. 3 parst of the loops separated by semi colons: 1. Declare and initialization 2. boolean conditional test 3. iteration
Catching an exception using try and catch 2
5. When no exceptions are thrown in the try block the execution will transfer to the line next to the end of the last catch statements. 6. If only one exception is thrown, the catch block related to that exception runs, after which the execution will transfer to the line next to the end of the last catch statement. 7. When an exception occurs the remaining lines of codes in the try block will never be executed. 8. Once control jumps to the catch block it never returns to complete the balance of the try block. 9. One of the benefits of using exception handling is that code to handle any particular exception that may occur in the governed region needs to be written only once. eg: There may be 3 different places in the try block that can generate my first exception, but wherever it occurs it will be handled by the same catch block.
Break Keyword
A break keyword in a switch statement execution will immediately more out of the switch block to the next statement after the switch. If break is omitted the program just keeps executing the remaining case block until either a break is found or the switch statement ends. Example: int x = 1; switch (x){ case 1: sysout ("x is one"); case 2: sysout ("x is two"); case 3: sysout ("x is three"); } sysout("out of the switch"); Whats the output to the previous code? Output is: x is one x is two x is three out of the switch because no break keyword so it "fall-through"
When does a for loop act as a while loop?
A for loop acts as a while loop when the initialization and increment sections is absent. Example: int i = 0; for ( ; i<10; ){ i++; //do some work }
Which if does the else clause belong to?
An else clause belongs to the innermost if statement to which it might possible belong (in other words the closet preceding if that does NOT have an else), See below: if (exam.done ( ) ) if (exam.getScore ( ) < 0.61) sysout ("Try again "); //which if does this else belong to? else sysout (" Java Master!"); Answer: Else belongs to the second if Statement
Checked Exception and Duck exception
Any method that might throw an exception (unless its a subclass of RuntimeException) must delcared 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 are exempt so the compiler won't check to see if you have declared them. But all non-RuntimeExceptions are considered "checked" exceptions, because the compiler checks to be certain you have acknowledged that "bad things could happen here". Each method must either handle all checked exceptions by supplying a catch clause or list each unhandled checked exception as a thrown exception. This rule is referred to as java's "handle or declare" requirement (sometimes called "catch or declare")
While loops2
Any variable used in the expression of a while loop must be declared BEFORE the expression is evaluate. Example: while (int x = 2){ }//not legal The key point about while loop is that it might not ever run. If the test expression is false the first time the while expression is checked, the loop body will be skipped.
if-else vs if, else if, else
Both are same but if, else if, else is recommended. if-else example: if (price <300){ buyProduct ( ); } else { if (price < 400){ getApproval ( ); } else { dontBuyProduct ( ); } } if, else if, else example: if (price < 300){ buyProduct ( ); } else if (Price < 400) { getApproval ( ); } else { dontBuyProduct ( ); }
Error
Both exception and error share a common superclass, throwable; thus both can be thrown using the throw keyword. When an error or a subclass of error (like Runtime-Exception) is thrown its unchecked.
Using break and continue
Break is used to stop the entire loop while continue is used to stop (skip) just the current iteration. Difference between two is whether or not to continue with a new iteration or jump the entire loop. Typically if you are using break or continue you will do an if test within the loop. Remember continue statements must be inside a loop; otherwise you will get a compiler error. Break statements must be used inside a loop or a switch statement. The break statement causes the program to stop execution of the innermost loop and start processing the next line of code after the block. The continue statement causes only the current iteration of the innermost loop to cease and the next iteration of the same loop to start if the condition of the loop is met.
Switch and case
Case arguments has to be resolved at compile time you can only use a constant or final variable that is immediately initialized with a literal value. Not enough to be final; it must be a compile time constant.
Do Loops
Do loops is similar to the while loop, except that the expression is not evaluated until after the do loop's code is executed. Therefore, the code in a do loop is guaranteed to execute at least once. Example: do { sysout ("Inside loop"); } while (false) ; sysout will print once even though the expression evaluated to false. Remember semiclon at the end of while.
Enhance for loop (For Arrays)
Enhanced for loop has 2 components instead of the traditional 3. Example: int [ ] a ={1,2,3,4}; //this is basic loop for (int x=0; x<a.length;x++) sysout (a[x]); for (int n:a) //enhanced for loop sysout(n); output = 1234 1234
Exceptions
Every exception is an instance of a class that has exception in its inheritance hierarchy. In other words, exceptions are always some subclass of the java.lang.exception. An actual catch clause looks like this: try { ---//some code here } catch (ArrayIndexOutOfBoundsException e){ ---e.printStacktrace( ); } In this example, e is an instance of the ArrayIndexOutOfBoundsException calss. As wth any other objects, you can call its methods.
throwing checked exception form a catch
If you throw a checked exception from a catch clause, you must also declare that exception. So, you must handle and declare vs handle or declare. Example: public void doStuff( ){ ---try{ ------//risky IO thing ---}catch (IOException ex){ ------//can't handle it ------throw ex;//cant throw it unless u declare it ---} } So, here the doStuff( ) method is clearly able to throw a checked exception. so the compiler will throw an error that you need to declare the exception even if you have a catch clause
Labeled Statements
It is most common to use labels with loop statements like for or while in conjunction with break and continue statements. A label statement must be placed just before the statement being labeled, an it consists of a valid identifier that ends with a colon (:). The labeled varieties are needed only in situations where you have a nested loop, and they need to indicate which of the nested loops you want to break from or from which of the nested loops you want to continue with the next iteration. A break statement will exit out of the labelled loop as opposed to the innermost loop, if the break keyword is combined with a label.
Categories of exception and errors for exam
JVM Exceptions: those exceptions or errors that are either exclusively or most logically thrown by the JVM. Programmatic exceptions: Those exceptions that are thrown explicitly by application and/or API programmers
Exception Declaration and the public interface
Just as a method must specify what type and how many arguments it accepts and what is returned, the exceptions that a method can throw must be declared (unless the exceptions are subclasses of runtimeexceptions). The list of the thrown exceptions is a part of a method's public interface. The throws keyword is used to list the exceptions that a method can throw. Syntax: Void myFunction( ) throws MyException1, MyException2 { -----code for the method here } Here this method has a void return type, accepts no arguments, and declares that it can throw one of the two types of exceptions. either type MyException1 or type MyException2. Just because the method declares that it throws an exception does NOT mean it always will. It just tells the world that it might.
Exam tip
Labeled continue and break statements must be inside the loop that has the same label name; otherwise the code will not compile.
Legal and Illegal Enhanced for loop int x; long x2; long [ ] la = {7L, 8L, 9L}; int [ ][ ] twoDee = {{1,2,3},{4,5,6},{7,8,9}}; String [ ] sNums = {"one","two","three"}; Animal [ ] animals = {newDog( ), newCat( )};
Legal for declarations: for (long y: la); for (int [ ] n : twoDee); for (int n2: twoDee[2]); for (String s: sNums); for (Object o: Snums); for (Animal a: animals); Illegal for declarations: for (x2:la)//x2 is already declared for (int x2:twoDee);//can't stuff an array into an int for (int x3:la);//can't stuff a long into an int for(Dog d:animals);// you might get a cat Enhanced for loop assumes that barring an early exit from the loop, you will always loop through every element of the array.
Whats wrong?? Exam tips for Exception Void doStuff ( ){ ----doMore( ); } void doMore( ){ ---throw new IOException( ); }
Look for code that invokes a method declaring an exception where the calling method doesn't handle or declare the checked exception. The following code uses the throw keyword to throw an exception manually but has two big problems that the compiler will prevent. First the doMore( ) method throws a checked exception but does not declare it. But suppose we fix the doMore( ) method as follow: void doMore( ) throws IOException{ .....} Then the doStuff( ) method is still in trouble because it too must declare the IOException, unless it handles it by providing a try/catch with a catch caluse that can take an IOException.
Scope of the loop variable
Multiple variable declaration needs to be separated y comma and must be the same type A variable declared in the for statement are all local to the loop and can NOT be used outside the scope of the loop. for (int i = 0; j =0; (i<10) && (j<10); i++,j++){ sysout ("i is " + i + "j is " + j); }
Is it legal to have more than one case label using the same value?
No. For example: int temp = 90; switch (temp) { case 80: sysout("80"); case 80: sysout ("80"); //wont compile! case 90: Sysout("90"); default: sysout("default"); }
Basic for loop: for loop issues
None of the 3 sections of the for declaration are required. The following example is perfectly legal, although not good practice: for ( ; ; ){ sysout ("Inside an endless loop"); } This is how for loops can have endless loops.
Exception Hierarchy
Object then throwable then error and exception then under exception, runtime exception
Whats the output? int x = 1; if (x == 3){ } else if (x<4){ sysout ("<4");} else if (x<2){ sysout ("<2");} else {sysout("else");} }
Output is <4 remember once an else if succeeds, none of the remaining else ifs nor the else will be tested.
Whats the output? static boolean doStuff ( ){ for (int x = 0; x<3; x++){ sysout("in for loop"); return true; } return true; }
Output is: in for loop cuz the return cause execution to leave not just the current iteration of a loop but the entire method. So the iteration expression never runs in that case.
Unchecked Exceptions
RuntimeExceptions error and all of their subtypes are unchecked exceptions and do not have to be specified or handled. Example: class Test{ ---public int MyMethod1( ) throws EOFException{ ------return MyMethod2( ); ---} ---public int MyMethod2( ) throws EOFException{ ----//code that actually could throw the exception ---return 1; ---} }
Declaration and Initialization: Scope of For Loops
Scope of variables declared in the for loop ends with the for loop. example: for (int x = 1; x<2; x++){ sysout (x); // legal } sysout (x); //Not legal, x is now out of scope and cant be accessed.
Method invocation in a switch statement
String S = "xy"; switch (s.length( ) ){ case 1: sysout ("length is one"); break; case 2: sysout("length is two"); break; default: sysout(" no match "); } Here the method being invoked on the object reference must return a value compatible with an int. Output is : length is two
General syntax of switch statements
Switch(expression){ Case constant1: code block Case constant2: code block default: code block 1. A switch expression must evaluate to "Sebics" (String, enum, byte, int, char, short), wont compile any other types 2. Case constant MUST be a compile time constant
Call Stack (Fig: 6-1)
The call stack is the chain go methods that your program executes to get to the current method. If your program starts in method main ( ) and main ( ) calls method a( ), which calls method b ( ), which in turn calls method c ( ), the the call stack consists of the following. c,b,a,main
If-else branching
The expression in parenthesis must evaluate to a boolean (true or false). Ex if (x>3) y = 3; //if ends here z += 8;//this will run regardless a = y + x; //this will run regardless
Subtypes and Supertype exceptions
The handlers for the most specific exceptions must always be placed above those for more general exceptions. For example: the catch clause for FileNotFoundException should be placed above the handler for the IOException, or else it will give a compiler error.
Creating your own exception
To create your own exception you simply subclass Exception (or one of its subclass) Class MyException extends Exception { } And if you throw the exception you must declare it. Class TestEx{ ---void doStyle( ){ ------throw new MyException( );//throw a checked exception this will upset the compiler because you have not delcared the exception you are throwing in the method.
While loops
Use while loop if you do NOT know how many times a block or statement should repeat, and continue looping as long as some condition is true. Syntax: While(expression){ //do stuff } expression (test) must evaluate to a boolean result. The while loop only executes if expression is true.
substring String s1 = javatpoint String s2 = s1.substring(0); String s3 = s1.substring(5,10); String s4 = s1.substring(5,15);
What are the 3 strings? s2 = Javatpoint s3 = point s4 will give an exception
Exception Matching
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 does not 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. This process is called exception matching.
Is t legal to box in a switch expression? PS: box means a conversion of a primitive type into their corresponding object wrapper classes. For eg: int to Integer, double to Double
Yes. Switch(new Integer(4)){ case 4: sysout ("boxing is ok"); }
Legal and Illegal if statement int trueInt = 1; int falseInt = 0; 1. if (trueInt) 2. if (trueInt == true) 3. if (1) 4. if (falseInt == false) 5. if (trueInt == 1) 6. if (falseInt == 0)
all illegal except 5 and 6
Label example for break statement
boolean isTrue = true; outer: for (int i =0; i<5; i++){ while (isTrue){ sysout("Hello "); break outer; }//end of inner while loop sysout ("Outer loop");// wont print }//end of outer for loop sysout("good-bye"); output: Hello good-bye
What happens if I switch on a variable smaller than an int?
byte g = 2; switch (g){ case 23: case 128: } This code will not compile because the second case argument (128) is too large for a byte.
Handling an entire class Hierarchy of exceptions
can actually catch more than one type of exception in a single catch clause. If the exception class that you specify in the catch clause has no subclass, then only the specified class of exception will be caught. However if the class specified in the catch clause does not have subclasses, the specified class will be caught as well. Pg: 344-345
Example of switch statement without break
classSwitchString{ pvsmsa{ String s = "green"[ Switch(s){ case "red": sysout ("red"); case "green": sysout ("green"); case "blue": sysout ("blue"); defualt: sysout ("done"); } } } In the example "green" matched so the JVM executes that code block and all subsequent code blocks. so the output is green blue done
Causes of early loop termination
code in loop and what will happen: 1. break: execution jumps immediately to the first statement after the loop 2. return: execution jumps immediately back to the calling method 3. system.exit ( ): all program execution stops; the VM shuts down.
Example of switch and case
final int a =1; final int b; b=2; int x=0; switch(x){ case a; //ok case b; //compiler error switch can only check for equality, other operator such as greater than are unusable.
Enhance for loop syntax
for (declaration:expression) 2 pieces are: 1. declaration: The newly declared block variable of a type compatible with the elements of the array you are accessing. This variable will be available within the for block and its value will be the same as the current array element. 2. expression: Must evaluate to the array you want to loop through. Could be array variable or method call that returns an array. The array can be any type: primitives, objects, or even arrays of arrays.
basic for loop syntax and example
for (declare/initialization; condition;iteration){ /* loop body */ } for (int i = 0; i<10; i++){ sysout(" i is " + i); }
Switch Statement comparison to if else
int x = 3; if (x==1) { sysout("x equals 1"); } else if (x==2){ sysout("x equals 2"); } else { sysout("No idea what x is "); }
Now Same code as switch statement
int x = 3; switch(x){ Case 1: sysout("x equals 1"); break; Case 2: sysout("x equals 2"); break; Default: sysout("No idea what x is"); } // Break statements in switch are optional
Default case: is the case which executes if it doesnt match any case. Default case does not have to come at the end of the switch
int x = somenumber betweenone and ten; switch (x){ case 2: case 4: case 6: case 8: case 10: sysout ("x is an even number"); break; } default: sysout ("x is an odd number"); } so if x is odd number it will print whats in the default clause
Label example for continue statement
outer: for (int i =0; i<5; i++){ for (int j =0; j<5; j++){ sysout ("Hello"); continue outer; }//end of inner loop sysout("outer");//never prints } sysout("good-bye"); output: Hello Hello Hello Hello Hello good-bye exercise: 6 -2 outer: while(int age=0; age<=21; age++){
Whats the output? int x = 2; switch(x){ case 2: sysout ("2"); default: sysout("default"); case 3: sysout("3"); case 4: sysout("4"); }
output is" 2 default 3 4 because there is no break.
Whats the output? int x = 7; switch(x){ case 2: sysout ("2"); default: sysout("default"); case 3: sysout("3"); case 4: sysout("4"); }
output is: default 3 4 The rule to remember is that default works just like any other case for fall through.
What to look for in exam? look for violation of switch and case arguments
switch(x){ case 0{ y = 7; } } // here the case uses a curly brace and omits the colon switch(x){ 0: { } 1: { } } //omits the keyword case
String equality
two strings will be considered equal if they have the same case sensitive sequences of characters. Example: String s = "Monday"; Swtich (s){ Case "Monday": //Matches! No Match example: String s = "MONDAY"; Switch (S){ Case "Monday": // strings are case sensitive, DOES NOT MATCH
int x = 1: switch (x) { case 1: { sysout ("x is one"); break; } case 2: { sysout ("x is two"); break; } case 3: { sysout ("x is three"); break; } } sysout("out of the switch"); Whats the result?
x is one out of the switch side note: Because fall-through is less than intuitive, oracle recommends that you add a comment such as //fall through when you use fall-through logic.