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("Prog1"); Object
Only constant variables are allowed: public
0.1 + False, workaround: a.equals(b) Compare
0.1 == Math.abs(0.1 + 0.1) < static final int HIGHWAY_MIN_SPEED Strings
0.2e6 = 60; "public static final" is optional.
0.3 StringBuilderbuilder = new
Same named methods in basic interface and StringBuilder("Hi");
a && b Only check b if a is true
super interface must have the same return builder.append(" you!");
a || b Only check b if a is false type. builder.insert(0, "XY"); String
0b11001 binary, leading "0b" Same named variables in basic interface and text= builder.toString();
super interface can have different return types.
0x1e hexadecimal, 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 (getClass() !=
int[10]; int[] x(int[] y)
obj.getClass()) {
Java primitive data types {return z})
return false;
boolean true, false int[][] m = 2 dimensional array
} else if (!super.equals(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 Arrays.equals( Compare array content Student other = (Student)obj;
a, b) return regNumber ==
int 32 bit, -231 to +231 -1
Arrays.deepEq Compare x dimensional other.regNumber;
long 64 bit, -263 to +263 -1, long x =
uals(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.equals(y) -> x.hashCode() ==
MONDAY, ...,
y.hashCode()
SUNDAY }
Java type casting
String a = new reference to String- Keywords
"Prog1"; Object "Prog1" (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 information loss
due inaccurate dataformat)
black arrows = explizit cast (heavy information
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 collections (cont)
package can be seen by all classes in this public int hashCode() { LinkedList<O add("ICTh"),
package return firstName.hashCode() + bject> l1 = add(int, "Bsys1"),
private can be seen only by this class 31 * surName.hashCode(); new remove(int),
static only once for all instances of this } LinkedList<> remove("ICTh"),
class (); contains("ICTh")
final can only be defined once and not Java compareTo example
Set<String> add("Test"),
changed later. Class: no
class Person implements s1= new remove("Test"),
subclasses, Method: no overriding
Comparable<Person> { TreeSet<>(); size() checks if already
static Means this is a constant
private String firstName, or added -> if so, return false.
final
lastName; Set<String> TreeSet = sorted, always
s2= new efficient. HashSet =
// Constructor…
Javadoc unsorted, usually very
@Override HashSet<>();
efficient
Start with /** end with */ each public int compareTo(Person
line * Map<Integer, get(key), put(key,
other) {
@author name author class / Object> m1= "Test"),
int c =
interface new remove(key),
compareStrings(lastName,
@version number version class / HashMap<>(); containsKey(key),
other.lastName);
interface or size(), TreeMap =
if (c != 0) { return c; }
@param name parameter method
Map<Integer, sorted by key, always
else { return
description Object> m2= efficient. HashMap =
compareStrings(firstName, unsorted, usually very
new
@return description returnvalue method other.firstName); }
TreeMap<>(); efficient
@throws/@exception potential method }
type description exception Iterator<String> it=
private int compareStrings(String
@deprecated deprecated method m1.iterator(); while(it.hasNext())
a, String b) {
description (outdated) {..}
if (a == null) { return b == null
? 0 : 1; }
Java inheritance
else { return a.compareTo(b); }
} Vehicle v1 = new Vehicle = static
} Car(); type, Car =
dynamic type
Java collections Object o = new Vaild -> Down-
Vehicle(); Vehicle Cast: Static type
ArrayList get(int), set(int,
v = (Vehicle)o; can be down
<Object> "OO"), add("CN2"),
casted
a1 = new remove(int),
ArrayList remove("CN1"),
<>(); contains("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 inheritance (cont) Java Lambdas / Stream API (cont) Nested class
Vehicle v = new Error -> Dynamic people.stream() .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.getLastName().contains( The inner class can use all members of the
if(v instanceof Test if dynamic type
pattern)) outer class (this include private members)
Car) { Car c = matches static type .forEach(System.out::prin Instantiation from outside eg
(Car)v;} tln); Polygon.Pointpoint=
super.variable Hiding: variable Random random= generate myPolygon.newPoint();
from super class newRandom(4711); random Can be declared in a method -> All variables
Stream.generate(random::n stream from outside are getting final eg Car
((SuperSuperClass) Hiding: variable
this).variable from "super.super" extInt) getSuperCar() { class SuperCar
class .forEach(System.out::prin extends Car { @Override public int
Dynamic dispatch: Methods: from dynamic tln); getMaxSpeed() {return 300; } }
typ and variables from static type. return newSuperCar();}
List<Person> list= stream to
peopleStream.collect(Coll collection
Java Lambdas / Stream API ectors.toList()); (List/Set/ Java own exception class
Map)
Collections.sort(people, sort public class MyException extends
ascending Person[] array= stream to
(p1, p2) -> p1.getAge() – Exception {
by age peopleStream.toArray(leng array
p2.getAge()); private static final long
th-> newPerson[length]);
serialVersionUID = 1L;
Collections.sort(people, sort by
(p1, p2) -> lastname Possible Stream API operations: public MyException(String msg) {
filter(Predicate), map(Function), super(msg);
p1.getLastName().compareT
mapToInt(Function), }
o(p2.getLastName()));
mapToDouble(Function), sorted(), }
people.stream().filter(p stream
distinct(), limit(long n),
-> p.getAge() >= 18) API
skip(long n), count(), min(), Java package import conflict order
.map(p -> example
max(), average(), sum()
p.getLastName()) 1. own class (inc. nested class)
2. single type imports -> import p2.A;
.sorted()
Comparator & Methodreference
3. type in own package -> package p1;
.forEach(System.out::prin
Inferface used to compare 2 Objects(before 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 methodrefernce
class:methodName eg
PersonComp::compareName
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 * assertEquals(expec actual «equals» Example: class Node<T extends Number
ted, actual) expected & Serializable>{ … }
1+ 1 to *
assertSame(expecte actual== expected Node<Integer> n1; // OK
1{2,5} min 2 max 5 (11..11111)
d,actual) (only reference Node<Number> n1; // OK
1{2,} min 2 max * (11, 111, etc.) comparation) Node<String> n2; // ERROR You can add
1{3} exactly 111 assertNotSame(expe expected != actual different Interfaces with & to ensure other
(only reference functionality like serializable
-?1 -1 or 1, "-" is optional cted, actual)
comparation) Wildcard type: Node<?> undefinedNode;
Mo|Di Or
assertTrue(conditi condition undefinedNode = new Node<Integer>
[a-z] any letter from a to z on) (4); undefinedNode= new
any letter from a to z or A to Z Node<String>("Hi!"); No read
[a-zA- assertFalse(condit !condition
Z] (.getValue()) and write (.setValue(X))
ion)
is allowed
\s whitespace assertNull(value) value== null
static variables with generics NOT allowed eg
. anything except newline assertNotNull(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.equals(y)) { returnx; }
\d any digit @Test(timeout=
5000) if(x.equals(z)) { returnx; }
\D not digit
if(y.equals(z)) { return y; }
@Test(expected= expect exception, if
(? name capture group -> String return null; } Call: Double d = test.
IllegalArgumentEx exception is thrown,
<Group Part1 = <Double>majority(1.0, 3.141, 1.0);
ception.class) test passes
1>REGE‐ matcher.group("Group1"); but also: int i = majority(1,1,3);
@Before public run this before
X) called type inference(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("Hi"); String s =
String input = scanner.nextLine();
(String)n.getValue();
@Test
Pattern pattern =
publicvoidtestPrime_2() {
Pattern.compile("([0-2]?[0- Serializable
9]):([0-5][0-9])"); assertTrue("2 isprime",
utils.isPrime(2)); Is a marker interface (is empty, just says that
Matcher matcher =
} this class supports it)
pattern.matcher(input);
Use it to say the developer that he can serialize
if (matcher.matches()) {
objects of this class, which means he can write
String hoursPart =
then in a bitecode and export them. Always
matcher.group(1); serialize all the objects contained in the
String minutesPart = mainobject
matcher.group(2); Use serialVersionUID to identify your class
System.out.println(..); (normally generated number) private
} static final long
serialVersionUID= -
6583929648459736324L;
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/
Serializable (cont)
Example:OutputStream fos= new
FileOutputStream("serial.bin") try
(ObjectOutputStream stream = new
ObjectOutputStream(fos)) {
stream.writeObject(person); }
Example:InputStream fis= new
FileInputStream("serial.bin") try
(ObjectInputStream stream = new
ObjectInputStream(fis)) { Person p =
(Person)stream.readObject(); … }
Java clone() method
public Department clone() throws Exception {
Department d = new Department();
d.name = name;
d.people = people;
d.subDepartments = new ArrayList<>();
for (Department subD : subDepartments) {
d.subDepartments.add(subD.clone());
}
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