Show Menu

OOv1 Cheat Sheet by

CheatSheet for the HSR information technology modul "Objektorientierte Programmierung 1" (object oriented programming 1)
regex     java     junit     maps     collections     lambdas     generics

Java basics

x = a ? b : c
a true? x = b, a false? x = c
0.1 + 0.1 == 0.3
False, workar­ound: Math.a­bs(0.1 + 0.1) < 0.2e6
a && b
Only check b if a is true
a || b
Only check b if a is false
0b11001
binary, leading "­0b"
0x1e
hexade­cimal, leading "­0x"
010 != 10
Leading 0 means octal
'A' == 'a'
False (case sensitive)
'A' < 'B'
True

Java primitive data types

boolean
true, false
char
16 bit, UTF-16
byte
8 bit, -128...127
short
16 bit, -32.768 ... 32.767
int
32 bit, -231 to +231-1
long
64 bit, -263 to +263­-1,­long x = 100l;
float
32 bit, float x = 100f;
double
64 bit, double x = 100d;

Java type casting

red arrows =implizit (probably inform­ation loss due inaccurate datafo­rmat)
black arrows = explizit cast (heavy inform­ation loss possible --> developer)

Java interfaces

Methods in intefaces are implicitly public and abstract and can't be private.
Only constant variables are allowed: public static final int HIGHWA­Y_M­IN_­SPEED = 60; "­public static final" is optional.
Same named methods in basic interface and super interface must have the same return type.
Same named variables in basic interface and super interface can have different return types.
Default methods: Basic interface doesn't have to implement default methods. If one method is not overriden, it just takes the default method.

Java reference types

int[] x = new int[10];
normal Array (public int[] x(int[] y){return z})
int[][] m = new int[2]­[3];
2 dimens­ional array
Array­s.e­qua­ls(a, b)
Compare array content
Array­s.d­eep­Equ­als(a, b)
Compare x dimens­ional array
public enum Weekday{ MONDAY, ..., SUNDAY }
Enum
String a = "­Pro­g1";
new reference to String­-Object "­Pro­g1" (if already exists, otherwise create it)
String c = new String­("Pr­og1­");
new String­-Object
a.equ­als(b)
Compare Strings
Strin­gBu­ild­erb­uilder = new String­Bui­lde­r("H­i"); builde­r.a­ppe­nd(­" you!"); builde­r.i­nse­rt(0, "­XY"); String text= builde­r.t­oSt­rin­g();

Java equals() example

@Override
public boolean equals(Object obj) {
  if (obj == null) {
    return false;
  } else if (getClass() != obj.getClass()) {
    return false;
  } else if (!super.equals(obj)) {
    return false;
  } else {
    Student other = (Student)obj; return regNumber == other.regNumber;
  }
}
If equals() is changed, hashCode() has also be changed! x.equa­ls(y) -> x.hash­Code() == y.hash­Code()

Keywords

public
can be seen by all that imports this package
protected
can be seen by all classes in this package and all subclasses of this
package
can be seen by all classes in this package
private
can be seen only by this class
static
only once for all instances of this class
final
can only be defined once and not changed later. Class: no subcla­sses, Method: no overriding
static final
Means this is a constant

Javadoc

Start with /**
end with */
each line *
@author name
author
class / interface
@version number
version
class / interface
@param name descri­ption
parameter
method
@return descri­ption
return­value
method
@throw­s/@­exc­eption type descri­ption
potential exception
method
@depre­cated descri­ption
deprecated (outdated)
method
 

Java hashcode() example

public int hashCode() {
    return firstName.hashCode() + 31 * surName.hashCode();
}

Java compareTo example

class Person implements Comparable<Person> {
  private String firstName, lastName;
  // Constructor…
  @Override
  public int compareTo(Person other) {
     int c = compareStrings(lastName, other.lastName);
     if (c != 0) { return c; }
     else { return compareStrings(firstName, other.firstName); }
 }
private int compareStrings(String a, String b) {
  if (a == null) { return b == null ? 0 : 1; }
  else { return a.compareTo(b); }
  }
}

Java collec­tions

Array­Lis­t<O­bje­ct> a1 = new ArrayL­ist­<>();
get(int), set(int, "­OO"), add("CN­2"), remove­(int), remove­("CN­1"), contai­ns(­"­CN1­"), size()
Linke­dLi­st<­Obj­ect> l1 = new Linked­Lis­t<>();
add("I­CTh­"), add(int, "­Bsy­s1"), remove­(int), remove­("IC­Th"), contai­ns(­"­ICT­h")
Set<S­tri­ng> s1= new TreeSe­t<>(); or Set<S­tri­ng> s2= new HashSe­t<>();
add("T­est­"), remove­("Te­st"), size() checks if already added -> if so, return false. TreeSet = sorted, always efficient. HashSet = unsorted, usually very efficient
Map<I­nteger, Object> m1= new HashMa­p<>(); or Map<I­nteger, Object> m2= new TreeMa­p<>();
get(key), put(key, "­Tes­t"), remove­(key), contai­nsK­ey(­key), size(), TreeMap = sorted by key, always efficient. HashMap = unsorted, usually very efficient
Itera­tor­<St­rin­g> it= m1.ite­rat­or(); while(­it.h­as­Next()) {..}

Java inheri­tance

Vehicle v1 = new Car();
Vehicle = static type, Car = dynamic type
Object o = new Vehicle(); Vehicle v = (Vehic­le)o;
Vaild -> Down-Cast: Static type can be down casted
Vehicle v = new Vehicle; Car c = (Car)v;
Error -> Dynamic type can't be down casted
if(v instanceof Car) { Car c = (Car)v;}
Test if dynamic type matches static type
super.va­riable
Hiding: variable from super class
((Sup­erS­upe­rCl­ass­)th­is).va­riable
Hiding: variable from "­sup­er.s­up­er" class
Dynamic dispat­ch: Methods: from dynamic typ and variables from static type.

Java Lambdas / Stream API

Colle­cti­ons.so­rt(­people, (p1, p2) -> p1.get­Age() –p2.ge­tAg­e());
sort ascending by age
Colle­cti­ons.so­rt(­people, (p1, p2) -> p1.get­Las­tNa­me(­).c­omp­are­To(­p2.g­et­Las­tNa­me(­)));
sort by lastname
peopl­e.s­tre­am(­).f­ilter(p -> p.getAge() >= 18) .map(p -> p.getL­ast­Name()) .sorted() .forEa­ch(­Sys­tem.ou­t::­pri­ntln);
stream API example
peopl­e.s­tream() .filter(p -> p.getL­ast­Nam­e().co­nta­ins­(pa­ttern)) .forEa­ch(­Sys­tem.ou­t::­pri­ntln);
pattern has to be final!
Random random= newRan­dom­(4711); Stream.ge­ner­ate­(ra­ndo­m::­nex­tInt) .forEa­ch(­Sys­tem.ou­t::­pri­ntln);
generate random stream
List<­Per­son> list= people­Str­eam.co­lle­ct(­Col­lec­tor­s.t­oLi­st());
stream to collection (List/­Set­/Map)
Person[] array= people­Str­eam.to­Arr­ay(­len­gth­-> newPer­son­[le­ngt­h]);
stream to array
Possible Stream API operat­ions: filte­r(P­red­icate), map(Fu­nct­ion), mapToI­nt(­Fun­ction), mapToD­oub­le(­Fun­ction), sorted(), distin­ct(), limit(long n), skip(long n), count(), min(), max(), average(), sum()

Comparator & Method­ref­erence

Inferface used to compare 2 Object­s(b­efore you used lamdas).
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

Nested class

Use this if a class is only used in another class
No seperate classfile
The inner class can use all members of the outer class (this include private members)
Instan­tiation from outside eg Polyg­on.P­oi­ntp­oint= myPoly­gon.ne­wPo­int();
Can be declared in a method -> All variables from outside are getting final eg Car getSup­erCar() { class SuperCar extends Car { @Override public int getMax­Speed() {return 300; } } return newSup­erC­ar();}

Java own exception class

public class MyException extends Exception {
 private static final long serialVersionUID = 1L;
 public MyException(String msg) {
   super(msg);
 }
}
 

Java package import conflict order

1. own class (inc. nested class)
2. single type imports -> import p2.A;
3. type in own package -> package p1; class X
4. Import on demand -> import p2.*;

Java regex

1*
0 to *
1+
1 to *
1{2,5}
min 2 max 5 (11..1­1111)
1{2,}
min 2 max * (11, 111, etc.)
1{3}
exactly 111
-?1
-1 or 1, "­-" is optional
Mo|Di
Or
[a-z]
any letter from a to z
[a-zA-Z]
any letter from a to z or A to Z
\s
whitespace
.
anything except newline
[^abc]
anything except a, b or c
$
end of string
\d
any digit
\D
not digit
(?<Gr­oup­1>R­EGEX)
name capture group -> String Part1 = matche­r.g­rou­p("G­rou­p1");
Example: Check daytime: ([0-1­]?[­0-9­]|2­[0-­3])­:[0­-5]­[0-9]

Java regex code example

String input = scanner.nextLine();
Pattern pattern = Pattern.compile("([0-2]?[0-9]):([0-5][0-9])");
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
  String hoursPart = matcher.group(1);
  String minutesPart = matcher.group(2);
  System.out.println(..);
}

Java JUnit

asser­tEq­ual­s(e­xpe­cted, actual)
actual «equals» expected
asser­tSa­me(­exp­ect­ed,­act­ual)
actual== expected (only reference compar­ation)
asser­tNo­tSa­me(­exp­ected, actual)
expected != actual (only reference compar­ation)
asser­tTr­ue(­con­dit­ion)
condition
asser­tFa­lse­(co­ndi­tion)
!condition
asser­tNu­ll(­value)
value== null
asser­tNo­tNu­ll(­value)
value!= null
fail()
everytime false
@Test­(ti­meout= 5000)
set test timeout
@Test­(ex­pected= Illega­lAr­gum­ent­Exc­ept­ion.cl­ass)
expect exception, if exception is thrown, test passes
@Before public void setUp() { … }
run this before each test
@After public void tearDown() { … }
run this after each test

Java JUnit examples

@Test
publicvoidtestPrime_2() {
  assertTrue("2 isprime", utils.isPrime(2));
}

Java generics

Example: class Node<T extends Number & Serial­iza­ble­>{ … } Node<I­nte­ger> n1; // OK Node<N­umb­er> n1; // OK Node<S­tri­ng> n2; // ERROR You can add different Interfaces with & to ensure other functi­onality like serial­izable
Wildcard type: Node<­?> undefi­ned­Node; undefi­nedNode = new Node<I­nte­ger­>(4); undefi­ned­Node= new Node<S­tri­ng>­("Hi­!"); No read (.get­Val­ue()) and write (.set­Val­ue(X)) is allowed
static variables with generics NOT allowed eg static T maxSpeed;
Generic Method: public <T> T majority(T x, Ty, T z){ if(x.e­qua­ls(y)) { returnx; } if(x.e­qua­ls(z)) { returnx; } if(y.e­qua­ls(z)) { return y; } return null; } Call: Double d = test.<­Dou­ble­>ma­jor­ity­(1.0, 3.141, 1.0); but also: int i = majori­ty(­1,1­,3); called type infere­nce­(also possible to mix types of argument)
Rawtype: like you would insert Object -> you need to down cast the elements. e.g. Node n; //without class n = new Node("H­i"); String s = (Strin­g)n.ge­tVa­lue();

Serial­izable

Is a marker interface (is empty, just says that this class supports it)
Use it to say the developer that he can serialize objects of this class, which means he can write then in a bitecode and export them. Always serialize all the objects contained in the mainobject
Use serial­Ver­sionUID to identify your class (normally generated number) private static final long serial­Ver­sio­nUID= -65839­296­484­597­363­24L;
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 {
 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;
}

Download the OOv1 Cheat Sheet

5 Pages
//media.cheatography.com/storage/thumb/higarigh_oov1.750.jpg

PDF (recommended)

Alternative Downloads

Share This Cheat Sheet!

Like this cheat sheet? Check out our sponsors!

Readability-Score.com is a collection of tools to make your writing better. More readabile content means higher conversion rates and better reader engagement. Measure website and document readability, measure keyword density and more!

Click Here To Get Started!

 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Regular Expressions Cheat Sheet
          Selenium WebDriver Cheat Sheet Cheat Sheet
          Eclipse Cheat Sheet