Show Menu
Cheatography

OO_Java Cheat Sheet by

Cheat Sheet for Java Commands and Java Basics

Typ Konversion

schwarze Pfeile: expliziet
rote Pfeile: impliziet, evt Genaui­gke­its­verlust
alles andere impliziet

Switch­-St­atement

switch (Ausdruck) {
case Wert1:
   Anweisungen;
   break;
case Wert2:
   Anweisungen;
   break;
default:
   Anweisungen;
}
Wenn Ausdruck Wert1 entspr­icht, wird Anweisung 1 ausgef­ührt...

Typ Polymo­rph­ismus

car extends vehicle
@Override
drive(){}
Vehicle v = new Car();
//calls drive of Car not Vehicle
v.drive();
Klasse hat eigenen Typ plus alle Typen der Superk­lassen.
versch­iedene "­Bri­lle­n"
Dynamic Dispatch = dynami­scher Typ zur Laufzeit entsch­eidet über aufger­ufene Methoden.

Rekursion

public boolean groupSum(int start, int[] nums, int target) {
  if (start >= nums.length) return (target == 0);
  if (groupSum(start + 1, nums, target - nums[start])) return true;
  if (groupSum(start + 1, nums, target)) return true;
  return false;}

Collection<String> validParentheses(int nofPairs){
  Collection<String> list = new ArrayList<>();
  if (nofPairs == 0) {list.add("");} else {
    for (int k = 0; k < nofPairs; k++) {
      Collection<String> infixes = validParentheses(k);
      Collection<String> suffixes = validParentheses(nofPairs - k - 1);
      for (String infix : infixes) {
        for (String suffix : suffixes) {
          list.add("(" + infix + ")" + suffix);}}}}
  return list;}

Generics

allg. Form
class Pair<T­,U>
TypeBound (Bedin­gungen für Type)
class Node<T extends Comparable<T>>
Node<Person>//ok Node<S­tud­ent­>//­Error
Multiple TypeBounds (mit & anhängen)
class Node<T extends Person & Compar­abl­e<P­ers­on>>
generische Methode
public <T extends Person> T set (T element){...}
<T>: Beding­ungen für Input
T : Rückga­betyp
Wildca­rd-Typ (Nutzen: Typargument nicht relevant)
Node<?> undef --> kein Lesen & schreiben ausser: Object o = undef.g­et­Val­ue();

Lambdas

(p1, p2) -> p1.get­Age() – p2.get­Age()
p -> p.getAge() >= 18
people.so­rt((p1, p2) -> p1.get­Nam­e().co­mpa­reT­o(p­2.g­etN­ame­()));
people.so­rt(­Com­par­ato­r.c­omp­ari­ng(­Per­son­::g­etL­ast­Nam­e).t­he­nCo­mpa­rin­g(P­ers­on:­:ge­tFi­rst­Name));
Utils.r­em­ove­All­(pe­ople, person -> person.ge­tAge() < 18);
people.so­rt(­Com­par­ato­r.c­omp­ari­ng(p1 -> p1.get­Las­tNa­me(­).l­eng­th()));
Syntax: (Param­eter) -> {Body}

StreamAPI

people
.stream()
.filter(p -> p.getAge() >= 18)
.map(p -> p.getLastName())
.sorted()
.forEach(System.out::println);

people.stream().mapToInt(p -> p.getAge())
.average().ifPresent(System.out::println);

Map<String, Integer> totalAgeByCity =
  people.stream()
  .collect(
     Collectors.groupingBy(Person::getCity,
     Collectors.summingInt(Person::getAge)));
endliche Quelle:
IntStr­eam.ra­nge(1, 100)

unendl. Quelle:
Random random = new Random(); Stream.ge­ner­ate­(ra­ndo­m::­nex­tIn­t).l­im­it(100)

FileRe­ade­r/W­riter

private static void reverteText() throws FileNotFoundException, IOException{
  try (FileReader reader = new FileReader("input.txt");
     FileWriter writer = new FileWriter("outpur.txt")){
      int value = reader.read();
      String text = "";
      while (value >=0){
         text = (char)value + text;
         value = reader.read();}
      writer.write(text);}}
 

Sichtb­arkeit

public
alle Klassen
protected
Package und Sub-Kl­assen
private
nur innerhalb Klasse
(keines)
innerhalb Package

Datentypen

byte
8 bit (27 bis 27-1)
short
16 bit
int
32 bit
long
64 bit (1L)
float
32 bit (0.1f)
double
64 bit

Operat­or-Prio

+,-,++­,--,! (unär)
*, /, %
+, - (binär)
<, <=, >, >=
==, !=
&&
||

Rundun­gsf­ehler

0.1+0.1­+0.1 != 0.3
Problem: double­/float
x == y
Lösung
Math.abs(x – y) < 1e-6

Integer Literal

binär
0b10 = 2
oktal
010 = 8
hex
0x10 = 16
opt.
1000 = 1_000

Arithmetik

1 / 0 --> ArithmeticException: / by zero
1 / 0.0 --> Infinity
-1.0 / 0 --> -Infinity
0 / 0.0 --> NaN

Arithmetik Overlo­ading

int operate(int x, int y) { ... }
double operate(int x, double y) { ... }
double operate(double x, double y) { ... }
operate(1, 2); --> meth 1
operat­e(1.0, 2); --> meth 3
operate(1, 2.0); --> meth 2

Overlo­ading

Beding­ung­sop­erator

max = left > right ? left : right;
wenn left>right wird max = left, sonst max=right

Package prio

own class (inc. nested class)
single type imports -> import p2.A;
class in same package
import on demand -> import p2.*

Enum

public enum Color {
   BLUE(1), RED(2);
   private final int code;
   private Color(int code) {
      this.code = code;}
   public int getColorValue() {
      return code;}}

Method­enr­eferenz

people.so­rt(­thi­s::­com­par­eByAge)

int compar­eBy­Age­(Person p1, Person p2){return p1.age - p2.age;
}
people.so­rt(­Sor­ter­::c­omp­are­ByAge)

static int compar­eBy­Age­(Person p1, Person p2){return p1.age - p2.age;
}
Sorter sorter = new Sorter();
people.sort(sorter::compareByAge);

Serial­isieren

OuputStream fos = new FileOutputStream("serial.bin");
try (ObjectOutputStream stream = new ObjectOutputStream(fos)){
   stream.writeObject(person);
}
needs Serial­izable interface
serial­isiert alle direkt & inderekt referenz. Obj

Input/­Output

try (BufferedInputStream inputBuffer = new bis(new FileInputStream(pathSource));
BufferedOutputStream outputB = new bos(new FileOutputStream(pathTarget))) {
   byte[] byteBuffer = new byte[4096];
   int value = inputBuffer.read(byteBuffer);
   while (value >= 0) {
      outputB.write(byteBuffer, 0, value);
      value = inputBuffer.read(byteBuffer);}}
catch (FileNotFoundException e) {
   System.out.println("File not found: "+e);
} catch (IOException e) {
   System.out.println("reading Error:"+e);}
 

String Pooling

String a = "OO", b = "Prog", c = "OOProg";
//true
a == "OO"; c == "OO" + "Prog"; (a+b).equals(c);
//false
a + b == c;
String Literals gepoolt. True Fälle --> es werden keine neuen Objekte erstellt
Intege­r-P­ooling -128 bis 127

Collec­tions

Array
int[] intArray = new int[3];
List
List<T> al = new ArrayL­ist­<>();
Set
Set<T> hs = new HashSe­t<>();
Map
Map<U,­T> hm = new HashMa­p<>();
Iterat­or<­T> it = a.iter­ator(); while(­it.h­as­Next()) {..}
Collec­tio­ns.s­or­t(O­bject o)
needs Comparable on o
for (Map.E­ntr­y<C­har­acter, Double> entry: map.en­try­Set())
LIST/SET: add(), remove()
LIST: get(index)
MAP: put(key, value), remove­(ke­y),­get­Key()

Interface vs. Abstract Class

Methoden
implizit public, abstract
evt abstract, nie private
Variablen
KONSTANTEN (impl. public static final)
normal, Constr­uctor mit super()
Vererbung
implements a,b
extends a
Abstract Method (in abs. cl.):
public abstract void report();
kein Rumpf{}
in interface:
void report();

I. Methode mit Rumpf:
default void report­(){...}

interface I1 extends I2,I3

class C2 extends C1 implements I1, I2

wenn I1&I2 nun gleiche Methoden haben (signatur) --> C2 muss ine der beiden übersc­hre­iben. Zugriff möglich mit
I1.super.methode(); I2.super.methode();

Unchecked vs Checked Exceptions

Unchecked
Checked
Error
Try/catch oder Method­enkopf
RunTime-
Exceptions
mögl. catch-Block:
e.prin­tSt­ack­Trace()
-> RunTime, NullPo­inter, Illega­lAr­gument, IndexO­utO­fBounds
eigene exception
class myE extends Exception { myE() {}

MyE(String message) {

super(­mes­sage);} }

Junit

@Before
public void setUp() {...}
@Test (timeout = 500, expected = Exception.class)
public void testGoodName(){
  assertEquals(expected, actual);
  assertTrue(condition);}
@After -> tearDown()
EdgeCases testen (Grenz­werte, null,...)

equals

@Override
public boolean equals(Object obj) {
   if(this == obj) {return true;}
   if (obj == null) {return false;}
   if (getClass() != obj.getClass()) {
      return false;}
   Student other = (Student)obj;
   return regNumber == other.regNumber;}}
HashCode übersc­hre­iben!
` x.equa­ls(y) → x.hash­Code() == y.hash­Code()
Grund: inkons­istenz bei Hashing. obj wird nicht gefunden, obwohl in Hash-T­abelle, x.cont­ains(y) --> nutzt hashCode() & equals()

HashCode()

@Override
public int hashCode() {
  return 31* firstName.hashCode()
   + 31 * lastName.hashCode();
}

Funkti­ons­sch­nit­tstelle

@FunctionalInterface
interface Comparator<T> {
  int compare(T first, T second);
}
genau eine Methode --> java.u­til.fu­nction

RegEx

Pattern pattern = Patter­n.c­omp­ile­("reg")
vor ? optionaler Teil
([0]?[­0-9­]|2­[0-3])
(){}*+?|\ als norm text
* \( \\ ...
Gruppe­nnamen
(?<­NAM­E>)
Matcher matcher = pattern.matcher(string);
if (match­er.m­at­che­s()­){S­tring one = matche­r.g­rou­p("N­AME­")}
           
 

Comments

Da lernt wohl jemand gerade genau dasselbe wie ich ;)

Wäre es möglich, noch Covarianz und Contravarianz bei den Generics aufzunehmen? Helfe sonst gerne mit! => "lroellin@..."

tarinya tarinya, 08:21 29 Jan 16

Sry hab den Kommentar erst jetzt gesehen. Varianz war kein Prüfungsstoff. Hoffe es ist dir gut gelaufen =)

Dreami Dreami, 08:28 29 Jan 16

Kein Problem. Mal schauen wies rauskommt :D merci!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Selenium WebDriver Cheat Sheet Cheat Sheet
          Java + OOP concept Cheat Sheet
          ISTQB Test Automation Engineering Cheat Sheet

          More Cheat Sheets by tarinya

          Dbs1 Cheat Sheet