Switch
switch(testHere){
case val1:
case val2:
//This is performed if testHere = val1 or val2
break;
case val3:
//This is performed if testHere = val3
break;
default:
//This is performed if testHere is something other than val1, val2 or val3
}
Switch values must be known at compile time and must be
- int (or byte, short) – or wrapper equivalent
- char – or wrapper equivalent
- String
- enum values
Values CANNOT be long, float, double or non-string classes.
Loops
while(condition) { … do stuff … } | Performed zero or more times |
do { … do stuff … } while(condition) | Performed one or more times |
for (initialisation; end condition; end of iteration action) { … do stuff … } | |
for (String myNextStr: myStringIterable) { … do stuff … } |
Try / Catch
Basic try clause
- Must have catch clauses or finally
- Finally clause always called at end – even after catch clauses
- First try-block exception takes priority, following exceptions “suppressed”
- Exceptions in finally block take priority and blast all others
try{
}catch(Exception1 ex1 | Exception2 ex2){
}catch(Exception3 ex3){
}finally{
}
Try-with-resources clause
- resources that implement AutoCloseable interface can be opened within the “try()”
- closed automatically in reverse order before leaving try clause (even if heading to catch)
- can still have a finally clause
try(… resource initialisation here...) {
}catch(Exception1 ex1 | Exception2 ex2){
}catch(Exception3 ex3){
}finally{
}