This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
pg. 1
SKILLCERTPRO
OCA Java SE 8 Programmer I Master
Cheat Sheet
1. Java Class Structure
Code style in the exam
Don't expect best practices
Really bad code there
The International Obfuscated C Code Contest: http://www.ioccc.org/
Class: building blocks. Template to create objects
Objects: runtime instances of classes
State: all objects of all our classes
Class members
Fields: class-level variables
Methods: functions, procedures
Method signature:
access modifier return type methodName(parameter type parameter name, ...)
pg. 3
SKILLCERTPRO
Valid class
public class Person { } ... class House { Person owner; int rooms; void cleanRoom(int roomNumber) {} }
Java building blocks
Classes
Interfaces
Enums (OCP)
😱 Spot errors
public class Main { public static void main(String[] args) { new House().rooms(); } } class House { String ownerName; int rooms; void cleanRoom(int roomNumber) { roomNumber = rooms; } int Rooms; int rooms() {} }
😱 Missing return statement
Easier with an IDE & compiler, right? :-D
pg. 4
SKILLCERTPRO
Comments
// one line Comments /* Multiline comment */ /* * Fancy Multiline comment * */ /** * * Java Doc comment (NOT IN THE EXAM) */
😱 Spot errors
// hello // world /* // hello world */ /* /* // Hello // World */ */
Rules .java source files
one public class in every file, at most
if there's one public class -> file name same as class
as much non-public classes as we want
😱 Spot errors
// Wolf.java
pg. 5
SKILLCERTPRO
class Wolf { } class wolf { }
😱 Spot errors
// House.java public class House { } class Person { } class Monkey { }
Main method
Entry point to our program
Java Runtime injects parameters
public static void main(String[] args) { }
Main method II
All valid
public static void main(String[] main) { // write your code here } public static void main(String... main) { // write your code here }
pg. 6
SKILLCERTPRO
public static void main(String m[]) { // write your code here }
😈 Watch out
public void main(String m[]) { // write your code here System.out.println("Hello"); }
public class Main { public static void main(String args) { new House().rooms(); } } class House { String ownerName; int rooms; void cleanRoom(int roomNumber) { roomNumber = rooms; } int Rooms; int rooms() { return rooms; } }
😱 Spot errors
public class Main { public static void main(String args) { // array of Strings! new House().rooms(); } } class House { String ownerName; int rooms; void cleanRoom(int roomNumber) {
pg. 7
SKILLCERTPRO
roomNumber = rooms; } int Rooms; int rooms() { return rooms; } }
Exercise: print all parameters from command line
if its a number?
JRE vs JDK
JRE: to run Java programs
JDK: to compile Java programs
JDK contains a JRE in order to run (test) programs
o inside the JDK folder there's a JRE with java command
o javac & other tools, only in JDK
Compiling from command line
$ javac -version $ java Main
Compile & run classes by hand. Read page 14
Imports
PIC: Package, Imports, Classes
import java.lang.*; by default
import one class or all classes in that package (wildcard)
non recursive
package name: lowercase legal identifiers separated by .
pg. 8
SKILLCERTPRO
😈 Watch out
Redundant
import java.lang.Exception; import java.lang.*;
Error
import java.lang..;
Packages as namespaces
avoid conflicts with two classes, same name
FQCN: Fully Qualified Class Name
default package == no package
😈 Watch out
Error!
import java.sql.Date; // try with * import java.util.Date; public class Main { public static void main(String m[]) { Date d; } }
Exercise
create our own packages, compile from command line
launch from command line java package.ClassWithMainMethod
Constructors
pg. 9
SKILLCERTPRO
methods to initialize objects after creation
creation in three phases
Stack (references), Heap (Objects, References)
😈 Watch out
public class A { String a = "Wow"; public A() { a = "much A's"; } public void A() { } public static void main(String m[]) { A a = new A(); } }
Using object fields (get & set values)
public class A { String a = "Wow"; String s = a + " much String!"; // reading field public static void main(String m[]) { A a = new A(); a.a = "Hello"; // setting field System.out.println(a.a); // reading field } }
Instance initializer blocks
public class Doge { String meme = "Wow!"; { meme += "Much instance initializer blocks ";
pg. 10
SKILLCERTPRO
} public Doge() { meme += " so exciting"; } public static void main(String[] args) { Doge d = new Doge(); System.out.println(d.meme); } { meme += " very confusing!"; } }
Instance initializer blocks
[fit] WAT
Instance initializer blocks
pg. 11
SKILLCERTPRO
only for people who doesn't know to chain constructors
to make code confusing
to build objects without using constructors
Java Reserved words
abstract boolean break byte case catch char class const continue default do double else extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while assert enum
Misterios
Transient: no se serializa esa propiedad (y asà no se graba a disco / envia por
la red)
Volatile: puede ser accedida por múltiples hilos: está sincronizada
Strictfp: compatibilidad operaciones floating point ^1
Goto: reservado ^2
Tipos primitivos vs. Clases Wrapper
boolean Boolean byte Byte char Character double Double float Float int Integer long
String s = "Hello"; s = "goodbye"; // original "Hello" object released
Creating my own inmutable classes
final class Person { private String name; Person(String name) { this.name = name; } public String getName() {
pg. 22
SKILLCERTPRO
return name; } } // after that code... Person diego = new Person("Diego"); diego.getName(); // setName() doesn't exists
Creating my own inmutable classes
// v2, with "setter" final class Person { private String name; Person(String name) { this.name = name; } public String getName() { return name; } public Person setName(String name) { return new Person(name); } }
Inmutable for what?
Parsing JSON / XML objects just read from the net
Using global settings in my app I don't want to change
In general, avoiding mutable state Is A Good Thing
Watch out!
String s = "hello"; String s1 = s.concat(" Mary Lou"); s.concat(" goodbye heart"); System.out.println(s1); System.out.println(s);
pg. 23
SKILLCERTPRO
Strings & the String pool
String s = "Hello"; String s1 = new("Hello");
Memory test
System.out.println("start"); try { Thread.sleep(3000); // 3 sec delay } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("lets go!"); List<String> list = new ArrayList<>(100000); for (int i = 0; i< 1000000; i++) { String s = "number"; // change for String s = new String("number"); list.add(s); } try { Thread.sleep(10000); // 10 sec delay } catch (InterruptedException e) { e.printStackTrace(); }
StringBuilder s = new StringBuilder("Apple Google Microsoft"); System.out.println(s); System.out.println(s.charAt(3)); s.append(" Yahoo!"); System.out.println(s);
Typical SQL statement
String query = "Select ( " + id + ", " + name + " ) from " + table + " where " + id + " = " + theId;
at least 10 String objects...
now 1000 customers connect to this page...
10000 objects in memory...
StringBuilder vs StringBuffer
StringBuffer: old, Thread safe
StringBuilder: shiny, shiny, new, not Thread safe, use this
Equality (== vs equals)
Sirve para ver la igualdad logica entre dos objetos
Object.equals compara referencias (es identico a ==)
Podemos sobreescribirlo
Sin equals no podemos usar estos objetos como Key en HashTable
@Override public boolean equals(Object obj) { // OJO: se recibe un Object if (obj instanceof Person2 && ((Person2)obj).getName().equals(getName()) ) { return true; } return false; }
consistente: si x.equals(y) devuelve true y no cambiamos nada, multiples
invocaciones devuelven siempre lo mismo
x.equals(null) --> false (con x no null)
equals - hashcode contract
Si dos objectos se consideran iguales mediante equals, deben devolver el
mismo hash code value
Invocaciones sucesivas sobre un mismo objeto que no cambiamos deben
devolver el mismo valor
NO es obligatorio que si dos objetos no son iguales (equals) deban devolver
hash codes distintos: pueden devolver siempre el mismo
Arrays
definition / instantiation
// good int[] a1 = new int[10]; int a2[] = new int[10]; Integer ai[] = new Integer[10]; // bad int a3[10] = new int[10]; int a4[] = new int[]; int a5[10] = new int[]; int a6[] = new int[](); int a6[] = new int(10);
public final void sayHello (String message) throws RuntimeException access | final | return | method name | parameter list | throws Exception list modifier | (optional) | type name |
a functional interface has exactly one abstract method
default methods in an interface have an implementation, they are not abstract
public class Main { public static void main(String[] args) { Downloadable d; d = uri -> { return uri + " Downloaded"; }; } } interface Downloadable { String download(String uri); }
List<String> names = Arrays.asList("Grouch", "Chicc", "Harp"); Predicate<String> p = s -> s.startsWith("G"); names.stream().filter(p).forEach(System.out::println);
Optionals
Optional<String> s = names.stream().reduce((s1, s2) -> { return s1+s2; }); if (s.isPresent()) { System.out.println(s.get()); }
Fun with functions
Interface Function<T,R> - T: the type of the input to the function - R: the type of the result of the function
// m1() takes a String and returns a String, hence the <String, String> static Function<String, String> m1() { return new Function<String, String>() { @Override public String apply(String s) { return s.concat(" and two boiled eggs!"); } }; }
class A { private int i1; int i2; } class B extends A { public B() { System.out.println(i2); i2 = 10; // OK, can see it System.out.println(i2); super.i2 = 11; // it's the same System.out.println(i2); this.i2 = 12; // same again System.out.println(i2); } }
Overloading vs. Overriding
override a method: same method in child class
overload a method: same method name, different parameters
Overriding checks
same signature
method in child class at least as accessible as method in parent class
can't throw new / broader checked exceptions
if returns a value, same type or sibclass of the method in parent class
(covariant returns) [^1]
[^1]: preserves the ordering of types
pg. 39
SKILLCERTPRO
final methods
can't be overridden
Redeclaring private methods
private methods can't be overridden
Static method hiding
no such thing as static method overridding exists
class A { public static void m1() { System.out.println("In A"); } } class B extends A { public static void m1() { // not "overridding", just same name System.out.println("In B"); } } A.m1(); // In A B.m1(); // In B A a = new B(); ((B)a).m1(); // In B
Hiding instance variables
that's why getters/setters are nice!
class A { private int i1; int i2; } class B extends A {
pg. 40
SKILLCERTPRO
int i1; // no problem, doesn't exist here String i2; // hiding instance vars! public B() { System.out.println(i2); i2 = "b"; // OK, String var System.out.println(i2); super.i2 = 11; // OK, int var System.out.println(super.i2); this.i2 = "b2"; // sOK, String var System.out.println(i2); } }
Abstract classes
a class that is marked as abstract
can't instantiate objects from this class
can have concrete & abstract methods
exercise: create an abstract class
excersise: extend an abstract class
Interfaces
method signature inside interfaces: public abstract always
marker interface: empty interface
variables inside interfaces: public static final always (static constants)
Interface inheritance
can inherit from multiple interfaces
interface I { void m1(); } interface II extends I {
pg. 41
SKILLCERTPRO
void m1(); public abstract void m2(); } class A implements II { @Override public void m1() { } @Override public void m2() { } }
Default methods in interfaces
public interface Test { public default int getInt() { return 1; } }
// can have more than one catch try { int i = 0; } catch (Exception e) { } catch (Throwable t) { } try { int i = 0; } catch (Throwable t) { } catch (Exception e) { // error: Exception has already been caught }
Creating your own exceptions
// Runtime, non-checked Exception class NonCheckedException extends RuntimeException { } // Compile-time, checked exception, handle or declare rule class CheckedException extends Exception { }
Catch-Or-Declare rule (Checked exceptions)
public class Main { public static void main(String[] args) { throwsNonChecked(); // no problem with non-checked try { throwsChecked(); } catch (CheckedException e) { e.printStackTrace(); } } static void throwsNonChecked() {
pg. 45
SKILLCERTPRO
throw new NonCheckedException(); } static void throwsChecked() throws CheckedException { throw new CheckedException(); } }
What does this prints? 😈
import java.io.IOException; public class Main { public static void main(String[] args) { try { System.out.println("DogeBegin"); new Main().saveToDisk(); } catch (IOException e) { System.out.println(e.getMessage()); } finally { System.out.println("DogeFinally"); } } void saveToDisk() throws IOException{ throw new IOException("Such litte space. Much files. Wow"); } }
What does this prints?
DogeBegin Such litte space. Much files. Wow DogeFinally
What does this prints? 😈
import java.io.IOException; public class Main { public static void main(String[] args) { try { System.out.println("DogeBegin"); new Main().saveToDisk(); } catch (IOException e) { System.out.println("IODoge" + e.getMessage());
DogeBegin IODogeSuch litte space. Much files. Wow DogeFinally
What does this prints? 😈
import java.io.IOException; public class Main { public static void main(String[] args) { new Main().run(); } void run() { try { System.out.println("DogeBegin"); saveToDisk(); } catch (IOException e) { System.out.println("IODoge" + e.getMessage()); return; } finally { System.out.println("DogeFinally"); } System.out.println("DogeReturn"); } void saveToDisk() throws IOException{ throw new IOException("Such litte space. Much files. Wow"); } }
pg. 47
SKILLCERTPRO
What does this prints?
DogeBegin IODogeSuch litte space. Much files. Wow DogeFinally
What does this prints? 😈
import java.io.IOException; public class Main { public static void main(String[] args) { new Main().run(); } void run() { try { System.out.println("DogeBegin"); saveToDisk(); } catch (IOException e) { System.out.println("IODoge" + e.getMessage()); return; } finally { System.out.println("DogeFinally"); } System.out.println("DogeReturn"); } void saveToDisk() throws IOException{ throw new RuntimeException("Such litte space. Much files. Wow"); } }
Exception in thread "main" java.lang.RuntimeException: Such litte space. Much files. Wow DogeBegin at Main.saveToDisk(Main.java:22) DogeFinally at Main.run(Main.java:11) at Main.main(Main.java:5) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
pg. 48
SKILLCERTPRO
OCA IZ0-808 Revision Notes
Exam Revision notes for OCA Java SE 8 Programmer I (1Z0-808)
Module 1: Before You Begin
Lesson 1: Why would I take the Oracle Certified Associate Java
Programmer Exam
1.1 Why would I take the Oracle Certified Associate Java Programmer Exam
Skipped
Lesson 2: The path to certification
2.1 The path to certification
Skipped
Lesson 3: Preparation strategies
3.1 Preparation strategies
Skipped
Lesson 4: Test Taking Strategies
4.1 How to take exam questions
Skipped
4.2 Prepare for exam questions, confidence, and other resources
Skipped
Module 2: Java Basics
pg. 49
SKILLCERTPRO
Lesson 1: Define the scope of variables
1.1 The meaning of scope, blocks and curly braces
The scope of a variable is where about in the program source you can use this
variable used by it's simple name (e.g. if you have a variable, egg in
class Food, Food.egg would not be classed as a simple name, whereas being able to
use jusrt egg would)
Initially, the scope of the variable is defined within the curly braces where it's declared
until those curly braces close.
1.2 Special cases of scope
These occur under simple for loops, and in the formal parameters of a method
Lesson 2: Define the scope of a Java class
2.1 Java class files:Contents and naming rules
Structure is: Package, then Import, then Class (package and imports are optional)
package mypackage; import myother.package.Here; import ohlook.here.are.morepackages.*; public class MyClass {...} class MyOtherClass {...} interface MyInterface {...}
Having more than one class/interface in a source file is unusual, but can be used.
It's only possible to have at most one public class or interface in one source file
2.2 Java classes: The class, member variables, methods and constructors
Within a class, we're allowed: (in any order, all elements in a class, unlike a method,
are collected together, so order does not matter)
o Method(s), static or non-static
o Constructor(s) (initialize objects of that class before they are made available
for regular use)
o Class(es), yes, you can declare a class inside another class :o
We can label as public so it's available from anywhere in our program, if we leave
this off then we can only use this class from within the package it was declared in
We can mark it as abstract which makes it impossible to create an instance of the
class
pg. 50
SKILLCERTPRO
o It can still contain variables or methods to be referenced elsewhere
o We usually use abstract classes as a base class for others to be derived
Lesson 3: Create executable Java applications with a main
method; run a Java program from the command line; including
console output
3.1 Creating executable Java applications with a main method
When the JVM starts, it looks for a method: main as an entrypoint
public static void main(String[] args) // alternatively, the following will function: public static void main(String $woo[]) public static void main(String _Name[]) public static void main(String... args)
public - accessible anywhere
static - no instance needed
void - nothing returned
main - name of method, must be called this
String[] - an array of string
args - purely convention, this can be anything
There are cases where we do not need to create a main method ourselves, e.g.
when bootstrapping with a framework, this framework will often encompass a
main method, we just provide plugin material
Java does not send a status code from the main method
o We can use System.exit(status) if we want to send a status code
We can overload the main method (same name but different types of
arguments), but there is no compelling reason and the JVM will not complain
(but won't get treated as the entrypoint)
3.2 Running Java from the command line
3.3 Managing the classpath
Directory structure must match package names
If we build from command line with javac, we must use -d flag
Supposing we have several classes (.class files, library classes are stored
in javalib from root, application code is stored in respective package structure from
pg. 51
SKILLCERTPRO
root, we need to specify a classpath comprising of our libraries and the location of
system libraries
java -cp /javalib:/home/example/things.Application would find code both
in /javalib and /home/example/things.Application (-classpath can also be used,
or set as an environment variable $CLASSPATH), we can also use /* notation to include
all files in directory
On Mac/UNIX/Linux, we use colons and foward slashes, whereas on Windows, it uses
backslashes and semi-colons
3.4 Working with console output
We can initialise a reference to the console by using:
Console c = System.console(); /* * System.console method might return null. * It usually does this if the program's I/O has been redirected */ if(c != null { c.printf(); c.format(); }
We can use this console object to instantiate a PrintWriter object:
o The variable stores the value that it represents (written directly to variable)
Reference types are: Float, Double (all non primitive types start with uppercase
letter)
pg. 57
SKILLCERTPRO
o We allocate at least 4 bytes that can point at/refer to an object location
o When we cahnge the object, the object in memory is simply changed (the
pointer is not)
The == operator compares two values to see if they're equal or not
o If we perform this on two primitives, it directly compares the values
o If performed on reference types, it will only return true if they're pointing to
the exact same reference in memory, even if both contents are the same
2.2 Understanding method argument passing
We always pass by value in methods
When we pass primitive values into a method, we copy the value, any changes made
in the method are only in the scope of the method, and do not change the initial
variable
When we pass an object, we pass a copy of the reference to the object, therefore any
changes to the object in the method change the original object
Lesson 3: Know how to read or write to object fields
3.1 Selecting a field from a reference expression
To access a field in an object, we either need to have a variable that refers to the
object directly, or an expression that resolves to a reference to the object
public class Thing { public int numOne; public long numTwo; } Thing t = new Thing(); // The variable t is an expression (value that has a type at compilation time, and has a value at runtime) t.numOne = 7; // This is a L-value expression (can be put on the left hand side of an assignment) int value = t.numOne // We can read value of t, and assign to value
We can also assign and read using array notation
public class Box { public Thing getOneThing() { return new Thing(); } } Box b = new Box(); b.getOneThing(); // Type Thing, produces reference to a Thing b.getOneThing().numOne // L-value expression, accessing Thing object created in method public Thing[] getManyThings() {
pg. 58
SKILLCERTPRO
Thing[] ta = // Partially initialise array with Things return ta; } Box b = new Box(); b.getManyThings(); // Type reference Array of Thing b.getManyThings()[0]; // Type reference to a Thing b.getManyThings()[0].numTwo; // Type long
3.2 Using "this" to access fields
public class Thing{ public int numOne; public void doStuff() { this.numOne = this.numOne + 10; } } Thing t1 = newThing(); Thing t2 = newThing(); // These point to two different Thing objects, each object has a field, numOne
Methods e.g. doStuff are assumed to belong to an object and the method executes
within the context of the object, known as this
this is an expression of the type of the enclosing class
Method code is read only, so it's easy to share with all objects which use that method
when using this
The this is just a copy of the object passed in to the method at invocation, and
during the scope of this, the object cannot be mutated from outside the method
A variable not prefixed with something-dot
o A method local variable
o Member variable with an implied this
o It's a static variable in a class that encloses the variable
o It's a static import from a class that does not enclose the variable
3.3 Code examples
package fieldaccess; public class Box { private Thing[] things = { new Thing(), new Thing(), new Thing() }; public Thing getOneThing() { return things[2]; }; public Thing[] getManyThings() { return things; };
pg. 59
SKILLCERTPRO
public void showThings() { System.out.println("Things:"); for (Thing t : things) { System.out.println(t.toString()); } } } package mainmethod; Box b = new Box(); System.out.println("numOne in a boxed thing is " + b.getOneThing().numOne); b.getOneThing().numOne = 5432 System.out.println("numOne in a boxed thing is " + b.getOneThing().numOne);
Returns:
numOne in boxed thing is 0; numOne in boxed thing is 5432
Lesson 4: Explain an Object's Lifecycle (creation, "dereference
by reassignment" and garbage collection)
4.1 Understanding allocation and referencing
The garbage collector is responsible for working out whether an object might be
used again, and for releasing any objects back to the heap memory when they are
identified as never to be used again
The system can only determine if it is not possible to use an object again
If an object can be used again, but is not used again, it has the possibility of memory
leak
An object is always accessible through a variable of reference type
o When this variable goes out of scope, it can be garbage collected
o If they can be used late,r they're called reachable and won't be subject to gc
o Only unreachable objects are elegible for garbage collection
o The risk of releasing an object prematurely is completely avoided
4.2 Collecting Garbage
aMethod() { StringBuilder sb = new StringBuilder();
If we set sb = null, the StringBuilder object becomes eligible for collection
Every executing method, including methods further up the call tree have live stack
frames
Every variable in a live stack frame is a live variable
Every object referred to by a live variable is a live object
pg. 60
SKILLCERTPRO
Every variable in a live object is a live variable
Any other object referred to by that variable is a live object
Lesson 5: Develop code that uses wrapper classes such as
Boolean, Double and Integer
5.1 Understanding and identifying wrapper objects, understanding autobixing
Wrapper classes let us associate behaviour with data, with integrity protections
We can use Java's (Java.lang.Object) generalization mechanisms, allowing any data
looked at this way to be referred to as an object
Primitives are not object, so we cannot use generalization
Primitives do not have the same kind of data associated as with objects
Wrapper classes let us see primitive types as objects, e.g. add numbers into lists
The compiler generates code to automatically create a wrapper around the primitives,
called autoboxing (or autounboxing in the context of unboxing primitives from
objects)
boolean -> Boolean char -> Character byte -> Byte short -> Short int -> Integer long -> Long float -> Float double -> Double
5.2 Investigating the API of Integer
Integer.BYTES // num of bytes used to represent int Integer.MAX_VALUE // max val can hold Integer.MIN_VALUE // min val can hold Integer.SIZE // num of bits used to represent int Integer(int value) // converts int to Integer Integer(String s) // converts string to int Integer.byteValue() // returns val as byte after primitive conversion Integer.compareTo() // compare objects numerically Integer.doubleValue() // val of int as double Integer.equals() // compares to other object
On the command line, we can define system properties with a -D, e.g.
java -Dmy.value=99 String val = System.getProperty("my.value"); // val is "99" Integer value = Integer.getInteger("my.value"); // val is 99
pg. 61
SKILLCERTPRO
Module 4: Using Operators and Decision constructs
Lesson 1: Use Java operators; including parentheses to override
operator precedence
1.1 Using operators, operands and expressions
Operators tell the compiler to run code, predefined in the system, more usually
operating on primitive types
Infix operator expression <operator> expression - operator in middle
Prefix operator <operator> expression
Postfix operator expression <operator>
Java does not permit programmer defined operator overloading (but + and - invoke
different code when working with floating point numbers, rather than integers)
1.2 Using arithmetic operators + - * / %
% operator is modulus
o 5 % 3 = 2
o 10 % 4 = 2
o -10 % 3 = -1
o -10 % -3 = -1
o -10.5 % -3.1 = -1.2
We can get overflow when we perform operands on numbers fitting in their
respective types, but the result does not fit in
o We get strange results, due to unsigned bits etc.
Division by zero represents arithmetic exception
Floating point overflow sets result to infinity (NaN)
1.3 Using the plus operator with Strings
The plus() operator can be used with either String or numeric types
o String + AnyType => String concatenation (the other type is converted to
string, possibly using the object's toString() method)
o NumericType + NumericType => Addition
o AnyOtherCombination => Compiler Error
Java expressions are evaluated left to right
o "Hello" + 1 + 2 = Hello12
o 1 + 2 + "Hello" = 3Hello
1.4 Promoting operands
Promotion means representing smaller numbers as larger ones
pg. 62
SKILLCERTPRO
if one operand is a double, the other is promoted to double else if one operand is a float, the other is promoted to float else if one operand is a long, the other is promoted to long else int
If you add short, char or byte, we get an int result
short s = 99; byte b = 10; s = b + s; // compiler error! (this is an int)
1.5 Using increment and decrement operators
We can increment or decrement L-values (values on left side of assignment)
int x = 99; int y = ++x; // Pre-Increment // y => 100 & x => 100 int x = 99; int y = --x; // Pre-Decrement // y => 98 & x => 98 int x = 99; int y = x++; // Post-Increment // y => 99 & x => 100 int x = 99; int y = x--; // Post-Decrement // y => 99 & x => 98 int[] xa = {0,1,2,3,4}; int idx = 0; System.out.println("value is " + (xa[idx++] >= 0 && idx > 0)); // Value is true int[] xa = {0,1,2,3,4}; idx = 0; xa[++idx] = xa[idx] + 1000; for (int v : xa) { System.out.println("> " + v); } /* * > 0 * > 1001 * > 2 * > 3 * > 4
Increment and Decrement operators result in an expression the same size as the
expression they're operating on (e.g. short, byte and char stay as they were)
We might only use this bit shifting for specific applications, e.g. network protocol
packets
We can use >>> for unsigned shifts, where extra bits don't come in (bringing in 0s
from the left rather than 1s) - this only works with Int and Long types
o If we try this with e.g. a short, we pad the left out with 0s, to the length of an
Int
1.7 Using comparison operators
< less than
<= less than or equal to
> greater than
>= greater than or equal to
These can be used on primitive and wrapper types, but not Number type
== equal
!= not equal
Strings that are the same share the same object, even if created differently,
therefore will return true when used with comparison
1.8 Using logical operators
! boolean not
o !(x > 99) == (x < 99)
~ tilde (bit pattern not)
o ~000 == 111
& and o 1 & 1 -> 1
| or o 0 || 0 -> 0
^ xor o 1 ^ 0 -> 1 o 0 ^ 1 -> 1 o 0 ^ 0 -> 0 o 1 ^ 1 -> 0
pg. 64
SKILLCERTPRO
1.9 Using short-circuit operators
&& - If first operand evaluates to false, second operand is never computed at all
|| - If first operand is true, then second is not calculated
o Both of these are only applicable to boolean values
1.10 Using assignment operators
int x, y, z; x = y = z = 0;
Arithmetic operators: +=, -=, *=, /=, %=
Boolean operators: &=, |=, ^=
Bitwise operators: <<=, >>=, >>>=
These operators do not promote values to int, the assignment operator casts its
computed result into whatever type the assignment is assigned to
The left hand side is guaranteed to be evaluated once, and once only
1.11 Understanding assignment compatibility
A char is unsigned, so a byte or short cannot represent or be represented by
a char
The case operator has HIGH precidence
int x = 99; short s = x; // CompileError short s = (short) x; // All ok using cast operation
We cannot cast non numeric types to numeric types (we can convert, however)
Autoboxing can create objects from primitive types, but these are conversions
1.12 Understanding other elements of expressions
<reference> instanceof <classtype> int x = 0; if (x instanceof Object) // Error, x is not reference String s = "Hello"; Class cl = String.class(); if (s instanceof cl) // Error, must be class literal if (s instanceof String) // Ok! String s = "Hello"; if (s instanceof Number) // Impossible, error null instanceof Object // Always false String s = null;
pg. 65
SKILLCERTPRO
if (s instanceof String) // Not executed, returns false
The instanceof operator tells us if we can cast the left hand value to the value on the
right
t -> reference to a thing . -> dot operator selects a member x -> member to be selected String s = "Hello"; s -> expression of type String . -> dot selects an element of expression length() -> identifies element to select, () calls method
1.13 Using parentheses and operator precendence
The precedence of multiplicative (multiplication, division and modulo) operations is
4.1 Using the general form of switch, case, break and default
int x = ?? switch(x) { case 10: { ...; break; } case 20: ...; break; default: ...; break; }
The case value must be computable at runtime (no method calls, like with what's
allowed when using if)
4.2 Code examples for the general form of switch
int day = 1 switch (day) { // Opening and closing braces necessary case 0: // Colon necessary System.out.println("Monday"); break; case 1: // Needs to be a constant expression System.out.println("Tuesday"); break; default: System.out.println("No Day!"); break; }
We do not need break statements, but the program will loop through all options
after matching case
4.3 Understanding break
If we omit the break statement, we will fall through and execute statements that are
otherwise associated with other cases
switch(x) { case 1: case 2: case 3: case 4: System.out.println("Weekday"); break; case 5:
pg. 68
SKILLCERTPRO
case 6: System.out.println("Weekend"); break; }
The program will print 'Weekday' for cases 1 through 4, and 'Weekend' for cases 5
through 6
The order of the cases matters to the logic of the code, the compiler works top down
Falling through just lets us hand-optimise code
4.4 Identifying switchable types
We're allowed to switch on: int, short, byte, String, char and enum (set of named
values)
We're not allowed to switch on: long, float, double, boolean
o Optimisation is built into the implementation of switching on Strings
Module 5: Creating and Using Arrays
Lesson 1: Declare, instantiate and use a one-dimensional array
1.1 Understanding simple array declarations, and variables of array type
Array declarations follow the basic variable initialisation structure:
int arrayOfInt[]; // Refers to array of integers int[] arrayOfInt; // Refers to array of integers int arrayOfInt[...]; // Refers to single int
1.2 Instantiating an array, array length
int[] aI; -> Array of integers, but we still need to instantiate it with the
assignment aI = new int[10];
o This creates an array of length 10
o As this is an array of int, each value is defaulted to 0
o Max size is about 8GB (20,000,00,000 int objects)
The length of array is determined by the number of elements in array (int expression)
pg. 69
SKILLCERTPRO
1.3 Initlaizing arrays by iteration, array indexes
int[] ai = new int[10];
These items are indexed from aI[0] -> aI[9]
Length of array is fixed at creation time and can never be changed
We can iterate through an array assigning values the following way:
int[] aI = new int[10]; for(int i=0; i<aI.length; i++) { aI[i] = getValue(); }
Arrays can also be used for Objects, e.g. StringBuilder
Each element is a reference variable to an Object, meaning each has a default value
(null for Objects)
StringBuilder[] sba = new StringBuilder[10] for(int i=0; i<sba.length; i++) { sba[i] = new StringBuilder("Hello" + i); }
1.4 Using a combined declaration and initialization of arrays
We can create an arrays and add values to it using the following:
int[] aI = {1, 2, 3, 4}; // Java doesn't mind about trailing commas int[] aI = {1, 2, 3, 4,}; Thing[] ta = { new Thing(), new Thing(99), existingThing };
1.5 Using immediate array creation not in a declaration
If we have a method:
public void doStuff(Thing[] ta) { ... }
We might like to provide an array to doStuff() without initialising a variable first doStuff(new Thing[] { newThing(), newThing(99 });
This makes it easy to tell the compiler what the base type should be
We are allowed literals, variables, expressions, object creation (expression of
the type object it creates) and null
pg. 70
SKILLCERTPRO
1.6 Initializing arrays by copying
Remember, arrays are fixed sizes
If we want a larger array, we can copy our array into another, larger, array
We can use System.arraycopy(<source array>, <starting index to copy>, <destination array>, <offset into destination array>, <num of items to copy>)
int[] aI = {1,2,3,4,5}; int[] aI2 = new int[10]; System.arraycopy(aI, 0, aI2, 0, aI.length);
We can now point the original aI to the new array: aI2 with aI = aI2;
Lesson 2: Declare, instantiate, initialize and use multi-
dimensional array
2.1 Declaring multi-dimensional arrays
These are constructed with <typename> <variablename>;
int[][] iaa; where int[] iaa[x] refers to a single array inside iaa where int iaa[x][y] refers to a single int
This can be instantiated with int iaa[][];
2.2 Using immediate initialization of multi-dimensional arrays
We can initialise in the standard curly brace method as follows:
o This creates 4 arrays, so 4 pointers (one for each inner array and a pointer for
2.3 Using iterative initialization of multi-dimensional arrays
int[] ia = new int[10]; // This creates one array, length 10 int[][] iaa = new int[2][3]; /* * This creates 3 arrays: * 2 Sub arrays of length 3 * 1 Holder array of length 2 */
And we're able to have arrays of different sizes, for example describe the size of
arrays of arrays, but not define the size of internal arrays:
int[][] iaa = new int[4][]; /* * We have created an array of 4 pointers * These all contain null values */ for(int i=0; i<iaa.length; i++) { iaa[i] = new int[i+1]; }
This loop code will make an array as follows:
{ {0}, {0,0}, {0,0,0}, {0,0,0,0} }
We are allowed to create int[4][], but not int[][4]
If we are performing a partial initialisation, we must add numbers to the brackets
from left to right
Arrays can be as deep as we want, e.g. int[][][][] iaaaa;
2.4 Code examples for multi-dimensional arrays
The following forms are legal:
Thing[][] taa; -> Pointer to Array of arrays
Thing[] taa[x]; -> Pointer to array of thing
Thing taa[x][y]; -> Pointer to individual thing
pg. 72
SKILLCERTPRO
Module 6: Using Loop Constructs
Lesson 1: Create and use while loops
1.1 Creating and using while loops
The basic while loop:
while(<boolean expression>) { <statement> }
The boolean statement can be a Boolean type (object), it will be unboxed at runtime
Test is made before entry, so loop body may never be executed
#### 1.2 Code examples of the while loop
We may accidentally make an infinite loop:
int x = 3; while ( x != 0) { System.out.println("x is" + x); }
Lesson 2: Create and use for loops including the enhanced for
loop
2.1 Understanding the simple use of the for loop
for(<setup>; <condition>; <prepare for next time>) { <programmer's code> }
2.2 Understanding the initialization section of the for loop
We can initialize many variables at a time:
for(int x=0, y=100, z; <test>; <next time>) { }
All variables initialized in the initialization section have to be the same type, but we
can use arrays:
We can only set variables of the same base type, other types are not allowed, as we
are not allowed to use semi colons again in this section
We are allowed to either declare variables or perform an expression in this section,
but not both
pg. 73
SKILLCERTPRO
for( int x=0, y=100, z, a[] = {1,2,3}, b[][], c = new int[5]; <test>; <ready for next> ){ <code here }
2.3 Understanding the test section of the for loop
Booleans will be unboxed to get the boolean primitive
This can result to false on first run, and never enter the loop
If we want to enforce at least one item: addUpNumbers(int first, int ... rest) {...}
Lesson 2: Apply the static keyword to methods and fields
2.1 Comparing class fields and object fields
Class Thing { private static int x;
pg. 80
SKILLCERTPRO
private int y; }
Each instance of Object of type Thing has a reference to type Class that it belongs to
Thing t = new Thing(); t.x; // Reference to x variable in Class Object t.y; // Reference to y variable in Thing object Thing t1 = new Thing(); t1.x; // Same reference as x t.x above t1.y; // New reference to y variable in Thing object
All objects in a class share the static fields of a class, but every object gets its own
version of a non-static field.
2.2 Using static on methods
Class Thing { private static int x; private int y; doStuff() {...} static doStaticStuff() {...} }
We usually invoke static methods with the classname, but it's legal to invoke with
instance name
o It ignores the instance it's invoked from
Thing t = new Thing(); t.doStuff(); Thing.doStaticStuff(); t.doStaticStuff();
We are not allowed to use this in static methods
Static should be used when we are dealing with properties or aspects of the thing
we're modelling that relate to the concept as a whole, rather than individual things.
2.3 Code Example
public class M7L2 { private int x; private static int y; public static void main(String[] args) { y = 99; System.out.println(y); // 99
pg. 81
SKILLCERTPRO
M7L2 object1 = new M7L2(); M7L2 object2 = new M7L2(); System.out.println(object1.y); // 99 System.out.println(object2.y); // 99 object1.x = 100; object2.x = 200; System.out.println(object1.x); // 100 System.out.println(object2.x); // 200 showY(); showX(); // Rejected, as we can not call this from a non static context object1.showX(); // X = 100, Y = 99 object2.showX(); // X = 200, Y = 99 } static void showY() { System.out.println(y); // 99 System.out.println(M7L2.y); // 99 System.out.println(this.y); // Rejected, as there is no this in static methods System.out.println(x); // Rejected, as x is not a static variable System.out.println(this.x); // Rejected, as there is no this in static methods } void showX() { System.out.println(x); System.out.println(y); }
Lesson 3: Create and overload constructors; including impact
on default constructors
3.1 Creating and overloading constructors
What is a constructor?
class Thing { Thing() {...}
Capitalization and spelling must be exact match
No return type (not even void)
We can pass normal argument lists
pg. 82
SKILLCERTPRO
We can provide accessibility specification, e.g. private, public...
We can provide a body if desired
To invoke the structure, we just use new Thing(<argument list>);
When we call new, the code does not jump straight into the body, there are a few
things first
o An object is created (memory allocated)
o If there is a parent class, the constructor for that will be called, this bubbles all
the way up to the parent class: java.lang.Object
o Instance initialisation is performed
o The constructor called runs
We are allowed to overload based on normal overloading rules
3.2 Differentiating between default and user defined constructors
class Thing { public Thing() { super(); } }
If we do not provide our own constructor, the compiler will create one for us,
the default constructor
Takes no arguments
Body just calls superclass constructor, which takes no arguments
If the superclass does not have this constructor, it errors
This constructor accessibility is the same as the class
o One exception: an enum always have private constructor (not on exam)
Lesson 4: Apply access modifiers
#### 4.1 Using the access modifiers public and private
public - accessible anywhere in program
private - visible inside the top level enclosing curly braces that surround its
declaration
o Aceessible to other classes, where we have class nesting
4.2 Using default access and the protected modifier
default - visible inside package
o we do not need to define, automatically default
protected - visible inside package and and subclasses
pg. 83
SKILLCERTPRO
Lesson 5: Apply encapsulation principles to a class
5.1 Designing for encapsulation
Ensure all member variables of a class are private
Best practice: allow modification of public variables, throwing Error if it's not updated
correctly
We use modifiers to seperate concerns between internal interactions and external
APIs
#### 5.2 Implementing encapsulation
Encapsulation helps us to know ehre to go in order to debug. It should also help
show to intended users to these classes that not part of the general API for use by
everyone.
We can make immutable objects final, just for clarity
public class Thing { private int x; public static final int y = 2; public static final String s = "Hello"; private static int z; private void modifyUtility() { ...; } void doStuff(AnyType a) { // validate here // throw error if invalud } }
Lesson 6: Determine the effect upon object references and
primitive values when they are passed into methods that
change the values
6.1 Changing values through method local variables
int x = 99; // 99 StringBuilder sb = new StringBuilder("Hello"); addOne(x); // 99 System.out.println(x); // 99 addOne(sb); System.out.println(sb); // "Hello world" void addOne(int x) { // x is copied to this variable, so the local variable ceases to exist x++; // 100
1.1 Understanding interface and implementation inheritance
A key concept of Object-Orientated programming is generalization, allowing us to
specify a base implementation, and allowing us to build on top of this
with specialization. This refers to the concept that specialization is just reverse-
generalization.
We can call this specialization two things:
Interface Inheritance
o Making or fullfilling a promise
o Contract to describe certain capabilities - subclass provides everything the
parent has, and can be more
o The parent class does not have to describe how each capability is coded
Implementation inheritance
o We specify code about how methods work in the parent class
o Anything we can do in parent, we can do in subclass
o We can modify behaviour provided by parent
1.2 Basic coding of implementation inheritance
class Thing { ... stuff ... } class SpecialThing extends Thing { ... stuff .. // from 'Thing' ... extended stuff of our own ...
1.3 Changing inherited behaviour
We can annotate with @override
To change behaviour, we need a class with the same name and an identical argument
list
pg. 86
SKILLCERTPRO
We need to make sure to override, rather than overload
class Thing { public void sayHello() { System.out.println("Hello"); } } class SpecialThing extends Thing { public void sayHello() { System.out.println("Bonjour"); } }
The method cannot be less accessible
It must be available in all the places the original method would have been
accessible
If we have a primitive return type, the override method must return the same
type
If we have an Object return type, we can return an object which is a subclass of
the type originally defined
1.4 Code examples
package m8l1b; public class Person { private String name; public String getName() { return name; } public void greet() { System.out.println("Hello " + name); } public Person(String name) { this.name = name; } } public class Friend extends Person { private String relationship; public Friend(String name, String relationship) { super(name); this.relationship = relationship; }
pg. 87
SKILLCERTPRO
public void haveRelationship() { System.out.println("Relationship with " + name); } @Override public void greet() { System.out.println("Hello " + name + " my " + relationship); } }
1.5 Philosophy and terminology of inheritance (part 1)
Encapsulation means the data members of an object should be manipulated only by
methods defined in that object. We do this by ensuring member variables are
marked private. Data integrity should be codified.
A well designed object should have carefully thought out paradigms, such as
constructors and static values to ensure it can be created correctly.
Specialization is the opposite of Generalization
Liskov Substitution is the idea that the specialized form must be a perfect substitute
for a generalized form
Interface inheritance differs from implementation inheritance in that no
implementation gets reused, the class implementing an interface does not gain
member fields or methods as default.
Interfaces promise behaviours
We are not allowed multiple implemetation inheritances, for sake of clarity
1.6 Philosophy and terminology of inheritance (part 2)
While overriding can change semantics of a method, it's not possible to remove
definition of a method.
Return type must be the same
The method must not be less accessible
The method may not throw checked exceptions that would have been illegal from the
base class
Polymorphism is the ability to look at something in multiple ways. It describes the
ability to look as the specialized form of something as the generalized thing.
Sometimes when we create private member variables, we can
use getters and setter to mutate these variables. class Thing { private String name;
pg. 88
SKILLCERTPRO
public String getName() { return name; } public void setName(String n) { name = n; } }
### Lesson 2: develop code that demonstrates the use of polymorphism
#### 2.1 Understanding the concepts of polymorphism
class Animal class Dog extends Animal Animal a = new Dog(); Animal[] zoo = new Animal[100]; zoo[0] = new Tiger(); zoo[1] = new Lion(); public void feed(Animal a) ... Dog d = new Dog(); feed(d); for (Animal a: zoo) { feed(a); }
#### 2.2 Code example
package m8l2; public class Animal { public String getName() { return "Unknown"; } public String eats() { return "Unknown"; } public void eat(String food) { System.out.println("Nom"); } } public class Lion extends Animal { private static final String FAV_FOOD = "Vegan"; @Override public String getName() { return "Larry"; } @Override public String eats() {
pg. 89
SKILLCERTPRO
return FAV_FOOD; } } public class Dog extends Animal { @Override public String getName() { return "Woofles"; } @Override public void eat(String food) { System.out.println("Nom Nom Nom Woof"); } } public class ZooKeeper { public void feedAnimals(Animal [] animals) { for (Animal a : animals) { String name = a.getName(); String food = a.eats(); System.out.println(name + " likes " + food); } } }
#### 2.3 Understanding the core teminology of polymorphism
A class can only have a single parent class, but that parent can have parents
Parent classes
o Base class
o Super class
o Generalization
o Interface
o Contract
Child class
o Derived class
o Sub class
o Specialization
We can either use extends for implementation inheritance, or implements for interface
inheritance
pg. 90
SKILLCERTPRO
2.4 Understanding variable type and object type
The type of the object may be the same type as the variable, or the type of the object
may be a specialization of the type of the object (subclass or implementation of an
interface).
If you invoke behavior on a variable, the compiler will use the type of the variable, or
it might be an expression actually, to determine whether or not that method is
possible for the things that variable might refer to
2.5 Determining object type
We can use two methods to find out class of object at runtime:
.getClass() method
instanceof type
2.6 Code examples
private static void showAnimalType(Animal a) { Class theClass = a.getClass(); String className = theClass.getName(); Class parentClass = theClass.getSuperClass();
Lesson 3: Determine when casting is necessary
3.1 Understanding the Liskov substitution principle and the "is a" relationship
SomeType t = aThing;
The thing your assigning must substitute seamlessly into the thing you're assigning
to
If type of aThing is SomeType, we do not need to cast
o If SpecialSubtype extends SomeType, we can
say SpecialSomeType implements SomeType
Animal a = theDog; // OK! Dog d = a; // ? /* * This is not true if Animal a = theCat; * We use: * Dog d = (Dog) a; * * This will compile OK, but throw a ClassCastException at runtime */
pg. 91
SKILLCERTPRO
3.2 Recognizing impossible assignments
There are some circumstances where assignments are not possible, e.g:
Animal a = theCactus; // Animal and cactus have no relation to each other Animal b = (Dog) theCat; // Sometimes allowed at runtime
The assignment may be possible if the reverse assignment could have also been
possible
3.3 Understanding casting with interface types in assignments
If we have:
Animal (class), with Tiger and Puppy
Pet interface, with Puppy and Rock
Animal a = (Animal) thePet;
If thePet was Puppy, this assignment is ok, but if it is Rock, then this is cannot be done,
and will throw a Runtime exception. Tiger t = (Tiger) thePet;
We do not need to cast this, but the assignment works anyway.
Where interfaces are concerned, providing we use a cast, the compiler will almost
always permit the assignment.
When final is used, we cannot create any subclasses of this class, this will reject any
assignments that would have been permitted without the final decleration.
Lesson 4: Use super and this to access objects and constructors
4.1 Understanding "this" for accessing object features
When we declare a variable and use it to refer to an object, this is a pointer to an
object. We can invoke a method by calling this reference.
Under these circumstances, code invoked by the instance of the object can be called
with this
The keyword this, which provides an explicit reference to the current context object.
4.2 Understanding "super" for accessing parent features
Using super makes the code instantiation look inside the parent class for the scope
class Base { int x; String getMessage() { return "Hello";
pg. 92
SKILLCERTPRO
} } class Derived extends Base { int x; public void method(int x) { super.x = 100; // Base x } String getMessage() { return "Hello" + "everyone!"; } // Instead of the above we can use: String getMessage() { return super.getMessage() + "everyone!"; } }
4.3 Understanding "this()" for accessing overloaded constructors
class Thing { private int x; public Thing() { x = 99; } public Thing(int x) { this.x = x; } }
Intead of the above, we should use:
class Thing { private int x; public Thing() { this(99) } public Thing(int x) { this.x = x; } }
Transfer control to another method for this class that takes a matching argument
4.4 Understanding "super()" for accessing parent constructors
A constructor is a special method to set up an object immediatlely after using new to
instantiate an object
pg. 93
SKILLCERTPRO
class Base { int x; Base(int x) { this.x = x; } } class Sub extends Base { int y; Sub(int x, int y) { super(x); this.y = y; } Sub(int y) { this(y, 100); } }
If we use super() to pass control to a parent class constructor, it must be the first
thing that happens in the constructor
We cannot construct a subclass without initialising the base class
o It always assumes super(); (no arguments)
4.5 Understanding the underlying principles of "this" and "super" for invoking other
constructors
Each subclass if built omn top of the parent class (with java.lang.Object being the
foundation)
It implicitly runs super() going foundations-upwards - if no constuctor matching this
signature is provided, we will receive a compiler error
We must call this or super first, we can choose one or the other
o super() always takes priority
4.6 Code examples
Sub(int x, int y) { super(this.calcValue(y)); // This is not allowed, as we need to initialise base class first } Sub(int x, int y) { super(Sub.calcValue(y)); // This is allowed, as calcValue is static }
Lesson 5: Use abstract classes and interfaces
5.1 Preventing instantiation
Once we have declared a class as being abstract, we will not be permitted to make an
invocation of new on that class directly.
pg. 94
SKILLCERTPRO
abstract lets us define constructors for classes which are accessible but prevent
those constructors from being called in any way other than by subclasses (by
using super())
5.2 Marking behaviours abstract
abstract class Animal { abstract String likesToEat(); }
Concrete classes must define implementation for this method likesToEat
All subclasses must either be abstract or define constructors for all abstract methods
5.3 Understanding the rules about abstract classes and methods
We can define constructors in abstract classes, and although they will not be called
by new, they can be called by super in subclasses
An abstract method can never be defined as private (it needs to be visible to the
subclass)
We cannot label an abstraxct method as final, as we want it to be overloaded in
subclasses to fulfill the promise of the contract
Abstract class needs not have abstract methods (can have concrete methods)
If we have a concrete class, we cannot declare abstract methods
If we have an abstract class but cannot implement all abstract methods in parent
class, this must be marked as abstract
5.4 Understanding and defining interfaces
We can have an interface with zero methods in
public interface Photographer { Image takePhoto(); int x = 99; // This does not create a variable int x; // Illegal, we need to define value }
All methods in an interface are public abstract (whether we say so or not)
All fields are public static final (initialisation must be immediate)
5.5 Implementing and using interfaces
We can implement more than one interface for a class, by providing a comma
seperated list
The extends clause preceeds the implements clause
Interfaces provide the ultimate in design for minimum knowledge
pg. 95
SKILLCERTPRO
5.6 Code example for interfaces
class Flyer { takeOff() } class Photographer { takePhoto() } class SpySatellite extends Asset implements Flyer, Photographer { public void takeOff(){...} public Image takePhoto(){...} }
5.7 Understanding the rules about interfaces
All methods in interfaces are public and abstract, but never final
Fields in interfaces are public, static and final
Constants in java should be ALL_UPPER_CASE
We are allowed interfaces which are specialisations of other interfaces by
using extends
5.8 Understanding static and default methods
A default method is an inheritable overridable instance method defined in an
interface, letting us have multiple implementation inheritance
Any method defined in an interface creates an obligation for every class that
implements that interface (that class must provide an implementation of the method)
default should only be used as a fallback
Module 9: Handling Exceptions
Lesson 1: DIfferentiate among checked exceptions,
RuntimeExceptions and Errors
1.1 Understanding exception types
Checked Exceptions -> Problems with the environment, e.g. user input
o We should write code to attempt to fix it
Unchecked Exceptions -> Should not happen
o RuntimeException
Errors (part of Unchecked) -> Problems external to the program
o Thrown by assert keyword (disabled by default for performance reasons)
pg. 99
SKILLCERTPRO
OutOfMemoryError
o Run out of memory
StackOverflowError
o Result of runaway recursion
IOException
o General input/output failures
SOAPException
o SOAP based web services call
SQLException
o Problems with databases
URISyntaxException
o Using HTTP and make malformed representation of resource trying to reach
XMLParseException
o Processing XML document
ArithmeticException
o Integer division of divide by zero
ArrayStoreException
o Putting wrong type of object in array
ClassCastException
o Casting invalid class
IndexOutOfBoundsException
o Tried to read non existant index
NullPointerException
o Object referred to as an unitialised object
Module 10: Working with selected classes from the
Java API
Lesson 1: Manipulate data using the StringBuilder class and its
methods
#### 1.1 Understanding the common StringBuilder constructors
String is a fundamental type built into a compiler, we can easily represent text
which can change easily using a StringBuilder (String is immutable)
StringBuilder Contructors
o public StringBuilder String s) o public StringBuilder(CharSequence cs) o public StringBuilder(int i) o public StringBuilder()
pg. 100
SKILLCERTPRO
The StringBuilder is able to automatically reallocate it's array, we should ensure the
StrinbBuilder is instantiated with a large enough size of storage array (by passing an
int) - start size is 16
If looking at worst case scenarios, we should pick smaller sizes and let the compiler
optimize
1.2 Using methods that modify StringBuilders
StringBuilder sb1 = new StringBuilder("Hello"); sb1.append(true); sb1.append(234); sb1.delete(7, 11); // First character to delete - First character after block to be deleted sb1.reverse(); sb1.setCharAt(2, 'A'); sb1.setLength(12); // Can be used to trunkate if shorter, else it will be oadded with `0` characters
1.3 Using methods that read and search in StringBuilders, and using methods that interact with
the internal storage of StringBuilders
We can use substring to read part of a StringBuilder
These do not change the text in the string buffer
They return new objects
StringBuilder sb = new StringBuilder("Yo"); sb.substring(0, 2); // Reads from 0 to 1 sb.charAt(3); // Returns char at index sb.getChars(3, 7, dest, 4); // First 2 is region to extract, 3rd is char array for the characters to be placed, the fourth is an offset into that array. sb.indexOf('yo'); // Returns index of start of parameter passed in sb.indexOf('yo', 7); // Same, but skips over leading characters sb.lastIndexOf('woo'); // Starts from back // These all return `-1` if value cannot be found sb.length(); // Length of array sb.ensureCapacity(int); // Grows the capacity to specified size (using multiple hops) sb.trimToSize(); // Ensures no memory wasted, will reallocate buffer