Lecture 8 and 9 - Strings, Arrays, Exceptions Flashcards
What is an immutable object ?
if its contents or state cannot be changed once it has been created.
Array characteristics :
size ==> fixed data type ==> primitives, objects get size ==> .length get item ==> [i] dimension ==> multi-dimensional
ArrayList characteristics :
size ==> re-sizable data type ==> objects get size ==> .size() get item ==> .get(i) dimension ==> one-dimensional
String objects are special. Why?
Creating a string: String s=”ok”;
String objects are immutable.
Contactinating strings: String s=”Ms “+”Elly”;
What is an exception ?
An exception is an abnormal event that arises during the execution of the program and disrupts the normal flow of the program.
When an error occurs during the running of a program in Java, an Exception object is automatically generated.
What is exception handling ?
Exception handling is to handle the runtime errors so that normal flow of the application can be maintained:
try-catch
try-catch-finally
Java exception classes are categorised into:
unchecked exceptions => is not checked during compilation.
checked exceptions => is checked during compilation.
Unchecked exceptions explenation
any exception that IS A SUBCLASS of RuntimeException (as well as RuntimeException itself).
are not checked by the compiler.
examples: ArithmeticException int a = 2/0; NullPointerException Rectangle r; r.getWidth(); NumberFormatException int i=Integer.parseInt("book"); ArrayIndexOutOfBoundsException int[] anArray = new int[3]; System.out.println(anArray[3]);
When an unchecked exception might occur, two options:
Don’t handle it - Do nothing.
Handle it with a try-catch or try-catch-finally
When a checked exception occurs, two options:
Don’t handle it - declare it, i.e. does not handle it inside this method, but propagate it down to the next method in the call stack.
public void methodsX() throws IOException{
____methodY();
}
Note: The keyword for declaring is throws, NOT throw.
catch it, i.e. handle the exception using try-catch or try-catch-finally. public void methodX(){ \_\_\_\_try { \_\_\_\_\_\_\_\_methodY(); \_\_\_\_} catch (IOException ex) { ...} }
Note: The exception categorization (unchecked or checked) affect compile-time behavior only; they are handled identically at runtime.
What is exception propagation?
When a method throws an exception, the JVM searches backward through the call stack for a matching exception handler.
If exists an handler, the rest of code is executed.
If no handler, print out the stack trace and exception type,and terminates the program.