You are on page 1of 5

OOv1 Cheat Sheet

by Philip Schmid (Higarigh) via cheatography.com/20304/cs/3111/

Java basics Java interfaces Java reference types (cont)

x = a ? a true? x = b, a false? x = c Methods in intefaces are implicitly public and String c = new new String​-
b : c abstract and can't be private. String​("Pr​og1​"); Object

Only constant variables are allowed: public


0.1 + False, workar​ound: a.equ​als(b) Compare
0.1 == Math.a​bs(0.1 + 0.1) < static final int HIGHWA​Y_M​IN_​SPEED Strings
0.2e6 = 60; "​public static final" is optional.
0.3 Strin​gBu​ild​erb​uilder = new
Same named methods in basic interface and String​Bui​lde​r("H​i");
a && b Only check b if a is true
super interface must have the same return builde​r.a​ppe​nd(​" you!");
a || b Only check b if a is false type. builde​r.i​nse​rt(0, "​XY"); String
0b11001 binary, leading "​0b" Same named variables in basic interface and text= builde​r.t​oSt​rin​g();
super interface can have different return types.
0x1e hexade​cimal, leading "​0x"
Default methods: Basic interface doesn't have Java equals() example
010 != 10 Leading 0 means octal
to implement default methods. If one method is
@Override
'A' == False (case sensitive) not overriden, it just takes the default method.
'a' public boolean equals​(Object obj) {

Java reference types if (obj == null) {


'A' < True
​ ​ ​ ​return false;
'B' int[] x = new normal Array (public
} else if (getCl​ass() !=
int[10]; int[] x(int[] y)
obj.ge​tCl​ass()) {
Java primitive data types {return z})
​ ​ ​ ​return false;
boolean true, false int[][] m = 2 dimens​ional array
} else if (!supe​r.e​qua​ls(​obj)) {
char 16 bit, UTF-16 new ​ ​ ​ ​return false;
int[2]​[3];
byte 8 bit, -128...127 } else {

short 16 bit, -32.768 ... 32.767 Array​s.e​qua​ls( Compare array content ​ ​ ​ ​Student other = (Stude​nt)obj;
a, b) return regNumber ==
int 32 bit, -231 to +231 -1
Array​s.d​eep​Eq Compare x dimens​ional other.r​eg​Number;
long 64 bit, -263 to +263 ​-1,​ long x =
u​als(a, b) array }
100l;
}
public enum Enum
float 32 bit, float x = 100f;
Weekday{ If equals() is changed, hashCode() has also be
double 64 bit, double x = 100d; changed! x.equa​ls(y) -> x.hash​Code() ==
MONDAY, ...,
y.hash​Code()
SUNDAY }
Java type casting
String a = new reference to String​- Keywords
"​Pro​g1"; Object "​Pro​g1" (if already
exists, otherwise create public can be seen by all that imports this
it) package

protected can be seen by all classes in this


package and all subclasses of this

red arrows =implizit (probably inform​ation loss


due inaccurate datafo​rmat)
black arrows = explizit cast (heavy inform​ation
loss possible --> developer)

By Philip Schmid (Higarigh) Published 25th January, 2015. Sponsored by Readability-Score.com


cheatography.com/higarigh/ Last updated 15th January, 2015. Measure your website readability!
Page 1 of 5. https://readability-score.com
OOv1 Cheat Sheet
by Philip Schmid (Higarigh) via cheatography.com/20304/cs/3111/

Keywords (cont) Java hashcode() example Java collec​tions (cont)

package can be seen by all classes in this public int hashCode() { Linke​dLi​st<​O add("I​CTh​"),
package ​ ​ ​ ​return firstN​ame.ha​shC​ode() + bj​ect> l1 = add(int, "​Bsy​s1"),
private can be seen only by this class 31 * surNam​e.h​ash​Code(); new remove​(int),

static only once for all instances of this } Linked​Lis​t<> remove​("IC​Th"),


class (); contai​ns(​"​ICT​h")

final can only be defined once and not Java compareTo example
Set<S​tri​ng> add("T​est​"),
changed later. Class: no
class Person implements s1= new remove​("Te​st"),
subcla​sses, Method: no overriding
Comparable<Person> { TreeSe​t<>(); size() checks if already
static Means this is a constant
private String firstName, or added -> if so, return false.
final
lastName; Set<S​tri​ng> TreeSet = sorted, always
s2= new efficient. HashSet =
// Constr​uctor…
Javadoc unsorted, usually very
@Override HashSe​t<>();
efficient
Start with /** end with */ each public int compar​eTo​(Person
line * Map<I​nteger, get(key), put(key,
other) {
@author name author class / Object> m1= "​Tes​t"),
​ ​ ​ int c =
interface new remove​(key),
compar​eSt​rin​gs(​las​tName,
@version number version class / HashMa​p<>(); contai​nsK​ey(​key),
other.l​as​tName);
interface or size(), TreeMap =
​ ​ ​ if (c != 0) { return c; }
@param name parameter method
Map<I​nteger, sorted by key, always
​ ​ ​ else { return
descri​ption Object> m2= efficient. HashMap =
compar​eSt​rin​gs(​fir​stName, unsorted, usually very
new
@return descri​ption return​value method other.f​ir​stN​ame); }
TreeMa​p<>(); efficient
@throw​s/@​exc​eption potential method }
type descri​ption exception Itera​tor​<St​rin​g> it=
private int compar​eSt​rin​gs(​String
@depre​cated deprecated method m1.ite​rat​or(); while(​it.h​as​Next())
a, String b) {
descri​ption (outdated) {..}
if (a == null) { return b == null
? 0 : 1; }
Java inheri​tance
else { return a.comp​are​To(b); }
​ } Vehicle v1 = new Vehicle = static
} Car(); type, Car =
dynamic type

Java collec​tions Object o = new Vaild -> Down-


Vehicle(); Vehicle Cast: Static type
Array​Lis​t get(int), set(int,
v = (Vehic​le)o; can be down
<O​bje​ct> "​OO"), add("CN​2"),
casted
a1 = new remove​(int),
ArrayL​ist​ remove​("CN​1"),
<>(); contai​ns(​"​CN1​"), size()

By Philip Schmid (Higarigh) Published 25th January, 2015. Sponsored by Readability-Score.com


cheatography.com/higarigh/ Last updated 15th January, 2015. Measure your website readability!
Page 2 of 5. https://readability-score.com
OOv1 Cheat Sheet
by Philip Schmid (Higarigh) via cheatography.com/20304/cs/3111/

Java inheri​tance (cont) Java Lambdas / Stream API (cont) Nested class

Vehicle v = new Error -> Dynamic peopl​e.s​tream() .filter(p pattern Use this if a class is only used in another class
Vehicle; Car c = type can't be down -> has to be No seperate classfile
casted final!
(Car)v; p.getL​ast​Nam​e().co​nta​ins​( The inner class can use all members of the
if(v instanceof Test if dynamic type
pa​ttern)) outer class (this include private members)

Car) { Car c = matches static type .forEa​ch(​Sys​tem.ou​t::​pri​n Instan​tiation from outside eg


(Car)v;} tln); Polyg​on.P​oi​ntp​oint=

super.va​riable Hiding: variable Random random= generate myPoly​gon.ne​wPo​int();

from super class newRan​dom​(4711); random Can be declared in a method -> All variables
Stream.ge​ner​ate​(ra​ndo​m::​n stream from outside are getting final eg Car
((Sup​erS​upe​rCl​ass​) Hiding: variable
th​is).va​riable from "​sup​er.s​up​er" ex​tInt) getSup​erCar() { class SuperCar
class .forEa​ch(​Sys​tem.ou​t::​pri​n extends Car { @Override public int

Dynamic dispat​ch: Methods: from dynamic tln); getMax​Speed() {return 300; } }

typ and variables from static type. return newSup​erC​ar();}


List<​Per​son> list= stream to
people​Str​eam.co​lle​ct(​Col​l collection
Java Lambdas / Stream API ec​tor​s.t​oLi​st()); (List/​Set​/ Java own exception class
Map)
Colle​cti​ons.so​rt(​people, sort public class MyException extends
ascending Person[] array= stream to
(p1, p2) -> p1.get​Age() – Exception {
by age people​Str​eam.to​Arr​ay(​len​g array
p2.ge​tAg​e()); ​private static final long
th​-> newPer​son​[le​ngt​h]);
serial​Ver​sionUID = 1L;
Colle​cti​ons.so​rt(​people, sort by
(p1, p2) -> lastname Possible Stream API operat​ions: ​public MyExce​pti​on(​String msg) {
filte​r(P​red​icate), map(Fu​nct​ion), ​ super(​msg);
p1.get​Las​tNa​me(​).c​omp​are​T
mapToI​nt(​Fun​ction), }
o(​p2.g​et​Las​tNa​me(​)));
mapToD​oub​le(​Fun​ction), sorted(), }
peopl​e.s​tre​am(​).f​ilter(p stream
distin​ct(), limit(long n),
-> p.getAge() >= 18) API
skip(long n), count(), min(), Java package import conflict order
.map(p -> example
max(), average(), sum()
p.getL​ast​Name()) 1. own class (inc. nested class)
2. single type imports -> import p2.A;
.sorted()
Comparator & Method​ref​erence
3. type in own package -> package p1;
.forEa​ch(​Sys​tem.ou​t::​pri​n
Inferface used to compare 2 Object​s(b​efore class X
tln);
you used lamdas). 4. Import on demand -> import p2.*;
Contains the method public int
compare(T o1, T o2) which you need to
override. Returns positiv number if o1 is bigger
then o2 and negative if oppisite 0 means that
they are equal

Instead of a comparator use method​ref​ernce


class:​met​hodName eg
Perso​nCo​mp:​:co​mpa​reName

By Philip Schmid (Higarigh) Published 25th January, 2015. Sponsored by Readability-Score.com


cheatography.com/higarigh/ Last updated 15th January, 2015. Measure your website readability!
Page 3 of 5. https://readability-score.com
OOv1 Cheat Sheet
by Philip Schmid (Higarigh) via cheatography.com/20304/cs/3111/

Java regex Java JUnit Java generics

1* 0 to * asser​tEq​ual​s(e​xpe​c actual «equals» Example: class Node<T extends Number


ted, actual) expected & Serial​iza​ble​>{ … }
1+ 1 to *
asser​tSa​me(​exp​ect​e actual== expected Node<I​nte​ger> n1; // OK
1{2,5} min 2 max 5 (11..1​1111)
d,​act​ual) (only reference Node<N​umb​er> n1; // OK
1{2,} min 2 max * (11, 111, etc.) compar​ation) Node<S​tri​ng> n2; // ERROR You can add

1{3} exactly 111 asser​tNo​tSa​me(​exp​e expected != actual different Interfaces with & to ensure other
(only reference functi​onality like serial​izable
-?1 -1 or 1, "​-" is optional cted, actual)
compar​ation) Wildcard type: Node<​?> undefi​ned​Node;
Mo|Di Or
asser​tTr​ue(​con​dit​i condition undefi​nedNode = new Node<I​nte​ger​>
[a-z] any letter from a to z on) (4); undefi​ned​Node= new

any letter from a to z or A to Z Node<S​tri​ng>​("Hi​!"); No read


[a-zA- asser​tFa​lse​(co​ndi​t !condition
Z] (.get​Val​ue()) and write (.set​Val​ue(X))
ion)
is allowed
\s whitespace asser​tNu​ll(​value) value== null
static variables with generics NOT allowed eg
. anything except newline asser​tNo​tNu​ll(​valu value!= null static T maxSpeed;
[^abc] anything except a, b or c e)
Generic Method: public <T> T

$ end of string fail() everytime false majority(T x, Ty, T z){

set test timeout if(x.e​qua​ls(y)) { returnx; }


\d any digit @Test​(ti​meout=
5000) if(x.e​qua​ls(z)) { returnx; }
\D not digit
if(y.e​qua​ls(z)) { return y; }
@Test​(ex​pected= expect exception, if
(? name capture group -> String return null; } Call: Double d = test.
Illega​lAr​gum​ent​Ex exception is thrown,
<Gr​oup​ Part1 = <​Dou​ble​>ma​jor​ity​(1.0, 3.141, 1.0);
c​ept​ion.cl​ass) test passes
1>R​EGE‐ matche​r.g​rou​p("G​rou​p1"); but also: int i = majori​ty(​1,1​,3);
@Before public run this before
X) called type infere​nce​(also possible to mix types
each test
void setUp() { … } of argument)
Example: Check daytime: ([0-1​]?[​0-
@After public void run this after each Rawtype: like you would insert Object -> you
9​]|2​[0-​3])​:[0​-5]​[0-9]
tearDown() { … } test need to down cast the elements. e.g. Node n;
//without class n = new
Java regex code example
Java JUnit examples Node("H​i"); String s =
String input = scanner.nextLine();
(Strin​g)n.ge​tVa​lue();
@Test
Pattern pattern =
public​voi​dte​stP​rim​e_2() {
Patter​n.c​omp​ile​("([​0-2​]?[​0- Serial​izable
9​]):​([0​-5]​[0-​9])​"); ​ ​ass​ert​Tru​e("2 isprim​e",
utils.i​sP​rim​e(2)); Is a marker interface (is empty, just says that
Matcher matcher =
} this class supports it)
patter​n.m​atc​her​(in​put);
Use it to say the developer that he can serialize
if (match​er.m​at​ches()) {
objects of this class, which means he can write
​ ​String hoursPart =
then in a bitecode and export them. Always
matche​r.g​rou​p(1); serialize all the objects contained in the
​ ​String minute​sPart = mainobject
matche​r.g​rou​p(2); Use serial​Ver​sionUID to identify your class
​ ​Sys​tem.ou​t.p​rin​tln​(..); (normally generated number) private
} static final long
serial​Ver​sio​nUID= -
65839​296​484​597​363​24L;

By Philip Schmid (Higarigh) Published 25th January, 2015. Sponsored by Readability-Score.com


cheatography.com/higarigh/ Last updated 15th January, 2015. Measure your website readability!
Page 4 of 5. https://readability-score.com
OOv1 Cheat Sheet
by Philip Schmid (Higarigh) via cheatography.com/20304/cs/3111/

Serial​izable (cont)

Exampl​e:​Out​put​Stream fos= new


FileOu​tpu​tSt​rea​m("s​eri​al.b​in​") try
(Objec​tOu​tpu​tStream stream = new
Object​Out​put​Str​eam​(fos)) {
stream.wr​ite​Obj​ect​(pe​rson); }

Exampl​e:​Inp​utS​tream fis= new


FileIn​put​Str​eam​("se​ria​l.b​in") try
(Objec​tIn​put​Stream stream = new
Object​Inp​utS​tre​am(​fis)) { Person p =
(Perso​n)s​tre​am.r​ea​dOb​ject(); … }

Java clone() method

public Department clone() throws Exception {


​Dep​artment d = new Depart​ment();
​d.name = name;
​d.p​eople = people;
​d.s​ubD​epa​rtments = new ArrayL​ist​<>();
for (Depar​tment subD : subDep​art​ments) {
​ ​d.s​ubD​epa​rtm​ent​s.a​dd(​sub​D.c​lon​e());
}
​return d;
}

By Philip Schmid (Higarigh) Published 25th January, 2015. Sponsored by Readability-Score.com


cheatography.com/higarigh/ Last updated 15th January, 2015. Measure your website readability!
Page 5 of 5. https://readability-score.com

You might also like