You are on page 1of 12

Class: template discribing state & behavior of objects of this type

Object: @Runtime + new make object of class = instance of


class own state & access
State: own unique set of instance variables of object
Behavior: methods
Identifiers: names for Java components. Some legal rules &
conventions.
Keywords: not used as identifiers
Inheritance: reusage in other classes. Ie. superclasses & subclasses.
Interfaces: 100% abstract superclass which methods to support,
but not how
Cohesive: every class focuesd set of responsibilities
Packages: organizing the classes use import to add them
Legal identifiers: rules of compiler whether name is legal
o Unicode characters
o Start letter, $ (currency), connecting char (ie _ ) NO DIGIT!
o After letters, currency, connecting, numbers
o No limit
o No Java keyword:
abstract assert (1.4) boolean break
byte
case
catch
char
class
const
continue default
do
double
else
enum (1.5) 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
o Case-sensitivity
Oracles Java Code Conventions: recommendations naming
classes, variables, methods
o Classes&Interfaces: CamelCase; nouns & adjectives
o Methods: lowerCamelCase; verb-noun pairs
o Variables: lowerCamelCase
o Constants (static&final): UPPER_CASE
Source file declaration rules:
o Only 1 public class per source code file
o Comments independent of any rule
o Public class must match filename (Eg public class Example
Example.java)
o If part of package package first line before import
o If import between package & class declaration

o Import & package apply to all classes in source code file


o File can have more than 1 nonpublic class
o File with no public class any name not matching classes in
file
Compiling with javac: javac [options] [source files]
Launching with java: java [options] class [arg]
public static void main(String[] args)
o Of String x Of String args[]
Fully qualified name package + class name
Import FQN OR * to get more than 1 class
Import static if a class contains static members, object references,
constants
Access modifiers !!!--> altijd kijken of code compileert!!!!
acces controls:
o public
o protected
o private
o no modifier = default/package
Nonaccess modifiers
o strictfp
o final
o abstract
Class access: creating instance, extending, accessing certain
methods & variables visibility
o public all classes from all packages access to public class,
but import needed @ different package!
o no modifier package only
Class nonaccess:
o final no subclassing/extending
o abstract no instantiation if 1 abstract method whole
class abstract.
Nonabstract methods are possible!

Interface: what, not how


o All methods public & abstract! -> NOT static
o All variables public, static, final constants
o Implemented by classes
o Can extend other (multiple) interfaces NOT implement
o public abstract interface == public interface
o public abstract void method() == void method() anything
else wont compile!
o public static final var=var

Class method access modifiers: public, protected, private


o public all classes accessible

OCP

o protected by inheritance (subclass) even if in different


package (but not by instance.var!!!) OR if in same package
o default in same package only
o private no access outside class
No (access) modifiers @ local variables, except final
Nonacces method modifiers: final, static, abstract, synchronized,
strictfp, native
o final prevents overriden
o final argument cannot be modified
o abstract declared, not implemented! must be
implemented by extended non-abstract class (not by extended
abstract class)
Never together with final or private!!!!
@ top-level not with static..
o synchronized only 1 thread at a time
o native implemented in platform-dependent code (C) no
implementation
o strictfp forcing floating points (IEEE 754)
variable argument lists
o arguments between () parentheses @ invocation of method
o parameters methods signature
o var-arg type specify the type of the argument(s)
o basic syntax var-arg int nameArray
[type+ellipsis+space+name]
o other arguments can be used as well
constructor declarations
o no return type
o same name as class
o no static, abstract or final!
variable declarations: final, public, protected, private, static,
transient, volatile
o primitives char (16 bit Unicode), boolean, byte, short, int,
long, double, float
small to big integer: byte (8 bit) short (16 bit) int (32
bit) long (64 bit) & float (32 bit) double (64 bit)
signed negative (1) / positive (0) = first bit @ left
o reference specific type; can be used to refer to subtype of
declared type
o instance inside class, outside method
4 access levels
final or transient
NOT abstract, synchronized, strictfp, native
instance != static
o shadowing: declare a local variable with same name as
instance variable
array declarations

o always object on the heap


o declare, construct, initialize
o IE int name [] / int[] name ; int[][] name / int[] name []
o No size of array in declaration!!!
final variables
o primitive: 1 time initialisation
o object: 1 time referencing
transient variables
o skip variable @ serialization
volatile variables
o (thread must reconcile own private copy)
static variables & methods, innerclasses, init blocks
o independent of instances

enums
o enum Name { VAR1,VAR2,VAR3 }
o outside class public or default modifier
o constructors -> is instantiated when instantiating 1 enum,
instance variables, methods, constant specific class body ->
overriding method of specific enum
o MyEnum.values() array of MyEnums values

Instance variable private


Accessor & mutators (get & set) methods public
get<property> & set<property>
Every class subclass of Object
Inheritance by extending classes
o Promote code reuse
o Polymorphism
IS-A extends class & implements interface
o Sub & super
HAS-A class has a reference to another class
Reference = variable one type & once declared never type
change
Reference type defines methods that can be invoked
Reference variable can refer to any object of same type as
declared ref & to any subtype
Reference variable declaration as class / interface type
Extend ONLY ONE
If overridden compiler knows this
Only reference is important to know methods; not instance
Rules:
o Equal argument list
o Same return type / subtype
o Access modifier not more restrictive

o Access modifier CAN be less restrictive


o Instance methods only overriden if inherited by subclass (not
private, final)
o Overriding method CAN throw unchecked execption regardless
overriden method declares exception
o Overriding method MUST NOT throw checked execptions that
are new or broader than declared by overriden method
o But can however throw narrower OR fewer exceptions
Keep in mind that compiler will still throw error of
overriden method if the reference is of this same
superclass
o Cannot override final method
o Cannot override static method
o If method cannot be inherited, it cannot be overriden
super.methodOverridenName() will invoke the overriden method
Overloading reuse same method name; different arguments
o MUST change argument list
o CAN change return type
o CAN change access modifier
o CAN declare new / broader checked exception
o Overloaded in same OR sub class
If object overloading reference type (not instance!) determines
which method!!!

Downcasting only when instanceof is of subtype


Upcasting it restricts number of methods you can invoke

interface implementation
o must have implementation of each method of interface
o no checked exceptions other than declared by interface
o maintain signature & return type of interface method
o if abstract class implementing interface no method
implementation needed!
o class can implement more than 1 interface
o interface can extend (more than 1!) other interface(s)
legal return types
o overloading = name reuse you cannot only change return
type! must change argument list
o overriding return type must be subtype of declared return
type (in 1.5)
o if primitive return type any value that can implicitly be
converted (thus for example char to int), or explicitly cast
declared
o returning object can be of subtype
constructors & instantiation
o Every class INCLUDING abstract, MUST HAVE constructor

o
o
o
o

o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o

Constructor has no return type & match class name


Typically used to init instance variables
new object constructor invoked at runtime
constructors can by any access modifier (incl private only
class itself can instantiate object of that type so class must
provide static method / variable that allows access to instance
creation within the class)
method can have same name as class but doesnt make it a
constructor
if no constructor default constructor always no-arg
if arg constructor must make a no-arg if needed
every constructor has first statement overload constructor
(this()) or superclass constructor (super())!!!
default constructor automatic super()
super() can include args
cannot access instance method/instance variable before super
constructor
only static variables & methods can be accessed by super or
this
abstract classes have constructors always called when
concrete subclass is instantiated
interfaces no constructors
constructor can only be invoked within another constructor
if superclass only has constructor with args & subclass no
constructor compiler error default constructor invokes
super() which does not exist!
Constructors are never inherited!
if using this(method()) method needs to be static, because
no instance can be invoked until after the super constructor
has run
some constructor will always make the call to super()!
if two constructors both calling eachother
StackOverflowError

o initialization blocks { x = 8; }
static class is first loaded
instance instance is created after call to super()!!!
order matters!
static variables & methods
o they belong to class, not instance
o main is static can only get static variables
o nonstatic cannot access static & static cannot access nonstatic
o static variable/method Classname.method() or
Classname.variable, but you can also use an object reference
(thus ref.variable or method())
o in constructors you can declare static & nonstatic variables!

o static methods cannot be overriden!!! (they can be redefined


however) reference needs to be subclass; it will not
automatically use method of subclass

primitive literal: source code representation of primitive data type


o Integer: decimal, octal, hexadecimal, binary
1000000 = 1_000_000 underscore used to clarify
number (cannot use it at beginning or end or next to
decimal point)
Binary literal: 0B101010 or 0b0001 prefix 0b
Octal: 0-7 07, 010 (=9) prefix 0
Hexadecimal: 0-9 & a-f (16 symbols not case sensitive)
prefix 0x 0xfff, 0xabcdef0123
o Long: same as integer with L/l suffix (bv 0xabcL)
o Floating-point: number decimal - number
Double: 8.8
Float: 8.8F less precise
No a comma but a dot!!!
o Boolean
true / false
o character
c; \u004E; prefix \u
number literal from 0-65535 is legal! (so binary, octal,
hexadecimal all legal) else needs cast
escape by \
Assignment
o Reference way to get to object
o primitive literal integer = int
byte b = 27 compiler casts like byte b = (byte) 27;
int or smaller expressions always int, thus:
byte a=3; byte b=8; byte c = a+b; compiler error
needs cast!!!
o Primitive casting
implicit widening conversion
explicit narrowing could lose info

From long -> double = ok; from double -> int without
cast not!
Example: byte b = (byte) 130L; -126 no error!
float assigment MUST have cast (float) OR f behind the
value!!!
If literal value (thus numeric value) is to high to assign
compiler error

128 to byte 10000000 is negative flip =


01111111 add 1 10000000 = -128
+= etc lets you add value without a cast! (implicit)
o Reference variable assignment
assignment can be a subclass
scope
o variable scope
from longest scope to shortest: static, instance, local,
block, init, constructor
{ int x=3; } only in brackets init block!
shadowing overlapping two scopes
when out of scope compiler error
initialization
o instance variables are initialized to default value
Object=null, byte,short,int,long=0, float,double=0.0,
boolean=false,char=\u0000
NullPointerException with object initalized to null!
Array instance all array elements have default values,
always!
o local variables
must ALWAYS be initialized before usage! else compiler
error
if a conditional block with init compiler complains it
might not have been initialized
object null is not the same as unitialized! local = not
null as default
Object references are copied, except for String
(=immutable)
o passing variables into methods
Object you pass copy of reference
Not pass-by-reference for objects pass-by-value
(variable-value) pass-by-copy-of-the-variable
Cant change callers ariable; but called method can
change object the variable is referencing to.
You cannot reassign a callers reference to a different
object in the called method: thus not Foo f=new Foo();
doStuff(f); doStuff(Foo g){ g = new Foo(); } f is now
referencing different object of g!
For primitives: pass-by-copy-of-the-bits-in-the-variable
o Garbage collection / objects lifecycle
Heap where objects live only 1 heap
JVM decides to run garbage collector
Each thread has own execution stack each own
lifecycle; can be alive or dead
(non-String) object is eligible for garbage collection when
no live thread can access it
Java can run out of memory

Methods to remove a object:


Remove reference by referring to null
Reassign a reference variable
Isolating a reference reference in reference if
first reference not reached (=null) then removed
finalize() run code before object is deleted by collector
method inherited by Object
for any object, finalize will be called once(!) by
garbage collector
calling finalize can save object from deletion

assignment operators
o size matters @ primitives
o reference variable is no object
o type matters at value
compound assignment opterators: +=, -=, *=, /=
relational operators: <, <=, >, >=, ==, !=
equality: numbers, characters, boolean primitives, object reference
.equals for String case sensitive!
instanceOf check if object reference variable is of particular
type.
o A null reference can also be tested always false of course.
o Compiler error @ two different class hierarchies!!! (if no
relation)
+, -, *, /
% modulus remainder of a division
When + sign with numbesr & String from left to right if first
numbers then numbers add + concate String. If first String then
all Strings concatenated.
increment/decrement operators: ++, -- if prefix, done before
expression, if postfix after this
o final variables cannot be changed! compiler error
conditional operator: x = (bool expression) ? value to assign if true :
value to assign if false;
logical operators: &, |, ^, !, &&, ||
o short-circuit (does not waste/perform pointless
evaluations): &&, ||
o non-circuit: &, |
o ^ exclusive-OR (XOR) ONE expression needs to be true (not
both)!
o ! boolean-invert opposite of booleans current value
(bitwise operators: &, |, ^)
String = Immutable Object!
o Each character 16-bit Unicode character
o Each declaration/editing new object creation!
o When using String method (e.g. concat, toUpperCase, replace),
but not referenced not changed

o String class final not overridable


o String s = ; one String object & ref var; String s = new
String() two objects, one ref var
o charAt(), concat(), equalsIgnoreCase(), length(), replace(),
substring(), toLowerCase(), toString(), toUpperCase(), trim()
StringBuilder not thread safe compared to StringBuffer
o Is a mutable object!
o Capacity: new StringBuilder() 16 chars capacity; new
StringBuilder(ab)16+arg length; new StringBuilder(int)
int-value
o Append, insert updates capacity automatically
o Insert after index of StringBuilders length exception
o append(value) update value with argument (String, boolean,
char, double, float, int, long)
o delete(int start, int end) start is zero-based; end is onebased
o insert(int offset, String s) offset is zero-based
o reverse()
o toString()
Arrays:
o declaring:
int[] key; int key[]; int[][] keys; int[] keys[];
NO SIZE OF THE ARRAY IN THE DECLARATION (NOT int[5]
key)!!!
o constructing:
creating array object on the heap how much space
size:
= new int[4];
multidimensional:
int[][] keys = new int[3][]; keys[0]=new int[5]; .
o initializing
object references not assigned are null!
with length you can loop through the array to init the
elements
o in one line: int[] dots = {6,7,8}; multidimensional: int[][] keys
= {{1,2,3},{4,5},{6,7}}
o anonymous array: int[] key; key = new int[] {2,3,4};
o arrays can only have one declared type! for primitives if
smaller bit its ok; for superclass subclass references ok
o if changing reference primitives has to be same type!!! (not
as above); for subclasses its ok
The Collection API: Lists, Sets, Maps, Queues
o List<Type> l = new ArrayList<Type>(); polymorphic
declaration
o java.util.List & java.util.ArrayList
o You can override Objects toString method for listing through
list!

o add(el), add(index, el), clear(), contains(el), get(index),


indexOf(el), remove(index), remove(el), size()

if(boolean expression){ }
o else { } optional
o else if(boolean expression) { }
o zonder {} alleen eerstvolgende regel geldt!
switch(expression: char, byte, short, int, enum, String){
o case outcome: { }
o use break!
o default: { } does not have to come at the end!
o outcome value MUST BE compile time constant!!!
o outcome value must meet expression type requirements (thus
byte type cannot take 128)
o no duplicate outcome value
o String: case-sensitive equality
while loop
o while(bool expression){ }
o do { } while(bool expression);
basic for
o for(declaration & initialization; boolean expression; iteration
expression){ }
o you can declare more of same type (!) by using commas (,)!
o break, return, System.exit() & exception cause loop
termination
o for( ; ; ;) legal!!! Some can be blank & for example bool exp
filled
advanced for
o for (type varName : list/array) { }
o break stop loop
o continue stop current iteration
o labeled loops:
exampleName: for() {}
used to define which loop to break / continue
break exampleName;
try{ } catch(Exception){ }
finally{ } always executed at some point after the try block
try{ } finally { } legal!
Exception propagation: the exception if not caught thrown to
bottom of call stack if @ main() halt JVM
Exception instance of class (subclass) of java.lang.Exception
Exception derived from Throwable ( Object). Error is also
derived from throwable (for example memory problems) can all
been thrown
printStackTrace()

catch if has subclasses caught as well


Exception handling at catch blocks goes from top to bottom so put
sub-exceptions first! else compile error exception already caught
Declare throwable exceptions in method; void method() throws ,
{ } not for RuntimeExceptions! (=unchecked) & Error
Handle or declare: throw or try-catch
Creating own exception: class MyException extends Exception{ }
catch(IOException e){ throw e; } also good but if checked also
declare it!
JVM Exceptions thrown by JVM
o ArrayIndexOutOfBoundsException: out of length of array
o ClassCastException: cast reference fails IS-A test
o NullPointerException: declared but not instantiated
(value=null)
o StackOverflowError: recursion too deeply
o ExceptionInInitializerError: initialize static variable in initializing
block
o NoClassDefFoundError: cant find class, because command-line
error, classpath issue, missing class file
Programmatic Exceptions thrown by application / API
programmers
o NumberFormatException: cannot convert String to number
o AssertionError (not exception): assert boolean test return false
o IllegalArgumentException: argument differently formatted as
expected one
o IllegalStateException: when state of environment doesnt
match operation

You might also like