Java Cheatsheet
Java Cheatsheet
the purpose of this cheat sheet is to briefly describe the core elements of Math.ceil(num)
the JavaScript language for those of studying it who have taken in much • rounds num up to nearest integer
more than we can hold onto well. nothing here is explained in full but rather Math.floor(num)
meant to get you on the right track. also, this document purposely does
• rounds num down to nearest integer
not cover browser-specific methods / syntax / objects and the like.
Math.max(num1, num2)
this cheat sheet is a work in progress and may be updated -- check
• returns larger num
back on occasion!
Math.min(num1, num2)
Math.pow(num1, num2)
Types
• returns num1 to the power num2
Type typeOf evaluation Primitive? Math.sqrt(num)
Array object no --an object arguments than shown here -- best to look them up for more info!
Note: array-like objects, for example arguments and NodeLists,
Symbol symbol no --an object
can also make use of these methods.
[] object no --an object arr.some(callback)
{} object no --an object arr.every(callback)
• returns a boolean value. returns true ifsome or every element in the
Number & Math Methods array meets the evaluation. example:
var a = [1,2,3];
someNum.toFixed(num)
var b = a.every(function(item){
• shortens someNum to have only num decimal places
num.toExponential() return item > 1;
• converts or coerces someValue to a string - someValue can be any type, optional "startVal" if supplied. an interesting example:
• converts a string into an integer. the optional radix argument defines the return prev;
base -- i.e., base 10 (decimal) or base 16 (hexadecimal).
Math.round(num)
• rounds num to nearest integer
• returns an array. filter returns an array of elements that satisfy a given function aFunctionName (args) {...
callback. example: • functions created in this manner are evaluated when the code is parsed
var arr2 = ["jim", "nancy", "ned"]; and are 'hoisted' to the top and are available to the code even before
var letter3 = arr2.filter(function(item) { they're formally declared. Note: Due to JS's odd construction, using
function declarations within a flow control statement can be wonky and is
return (item.length === 3);
best avoided.
}
);
Function Expression / Anonymous Functions
c
onsole.log(letter3); // ['jim', 'ned']
var bar = function (args) {...
arr.sort(function(){..})
• (also referred to as 'Function Operators') anonymous functions are
• returns the original array, mutated. sort returns the elements sorted with evaluated at 'runtime' and are therefore less memory intensive. they must
a given criteria. for example: be provided a variable name but need not have a function name
var stock = [{key: “r”, num: 12}, {key: “a”, num: (therefore: anonymous). [these are ]
2}, {key: “c”, num: 5}]; Named Function Expression
var c = stock.sort(function(a,b) { var bar = function foo (args) {...
return a.num - b.num; • confusingly, this is still an 'anonymous function.' assigning a name is
} ); // [ { key: ‘a', num: 2 }, { key: ‘c', num: 5 useful for debugging purposes and also allows for self-referential /
recursive calls
}, { key: ‘r', num: 12 } ]
Function Constructor
arr.map()
var anotherFunction = new Function (args, function
• returns an array. map goes over every element in the array, calls a
() {... }) {...}
callback on the element, and sets an element in the new array to be equal
to the return value the callback. for example: • equivalent to a functional expression
var stock = [{key: "red", num: 12}, {key: "blue", Self-Invoking Anonymous Functions
( function (args) { doSomething; } ) ( );
num: 2}, {key: "black", num: 2}];
• (also known as IIFEs / 'Immediately Invoked Function Expressions') and
var b = stock.map(function (item){
invokes immediately
return item.key;
}) // ["red","blue","black"]
Loops / Control Flow Statements
arr.forEach()
if .. else if .. else
• no return value. forEach performs an operation on all elements of the
array. for example: if (considtion1) {
Loops / Control Flow Statements (cont) String Methods, Properties & Etc (cont)
"this" one.concat(two)
• concatenates string/array one with two
coming soon JSON.stringify( )
• converts a javascript value/object into a string
String Methods, Properties & Etc JSON.parse ( )
a string can be coerced into an array so many array methods are • converts a JSON string into a javascript object
applicable as well
Date Methods
str.charAt(num)
Note: Unix epoch is January 1, 1970
• returns the character in str at index num
var today = new Date();
str.charCodeAt(num)
• creates date object for now
• returns the unicode value of the char
var someDate = new Date("june 30, 2035");
String.fromCharCode(num)`
• creates date object for arbitrary date
• returns the character with unicode's num
var today = Date.now();
str.indexOf(char)
• returns -1 if char not found in str
str.lastIndexOf(subString)
• returns number of milliseconds since epoch Note: index numbers for arrays start at 0
parse() arr.length()
• returns milliseconds between date and Unix epoch. arr. push(val)
toDateString() • adds val to end of arr
toTimeString() arr. pop()
toLocalTimeString() • deletes last item in arr
arr. shift()
break; itemsA..
• stops current loop iteration and increments to next Higher Order Functions
isNaN(someVar)
functions that accept other functions as an argument
• returns true if not a number
isFinite(someVar) Scope
var aVar = anObject[anAttribute] || "nonesuch"; the set of variables, objects, and functions available within a certain
• assigns a default value if none exists block of code
var aVar = anEvaluation ? trueVal : falseVal;
Callback
• ternary operator. assigns trueVal to aVar if anEvaluation is true, falseVal
(also event handler) a reference to executable code, or a piece of
if not
executable code, that is passed as an argument to other code.
delete anObject[anAttribute]
(aProperty in anObject) the % operator
• returns true or false if aProperty is a property of anObject % returns the remainder of a division such that "3 % 2 = 1" as 2 goes
eval(someString) into 3 once leaving 1. called the "remainder" or "modulo" operator.
• evaluates a someString as if it was JavaScript. i.e. eval("var x = 2+3")
Composition
returns 5
the ability to assemble complex behaviour by aggregating simpler
behavior. chaining methods via dot syntax is one example.
Chaining Method
also known as cascading, refers to repeatedly calling one method an object property has a function for its value.
after another on an object, in one continuous line of code.
where two or more identifiers in a given namespace or a given scope abstract arguments boolean break
cannot be unambiguously resolved byte case catch char
DRY class const continue debugger
(also ECMA-262) the specification from which the JavaScript extends false final finally
implementation is derived. version 5.1 is the current release. float for function goto
refers to the number of arguments an operator takes. ex: a binary instanceof int interface let
function takes two arguments long native new null
Currying package private protected public
refers to the process of transforming a function with multiple arity into return short static super
the same function with less arity switch synchronized this throw
Recursion throws transient true try
Callback Hell
Closure
a function with access to the global scope, it's parent scope (if there is
one), and it's own scope. a closure may retain those scopes even after
it's parent function has returned.
IIFE
Encaps The process of binding related Using access Interface Blueprint of a class. It contains only static, final Used:
ulation classes, objects and operations modifiers, variables and only unimplemented methods. to
together is called Encapsulation packages Classes implement the interface should support
Abstra‐ The process of specifying what to do Using abstract implement all methods of the interface, or be multiple
ction without specifying how to do it classes and declared abstract inheri‐
interfaces tance
Inheri‐ When one class inherits the Using Aggreg‐ Abstract classes don't support multiple inheritance, whereas
tance properties of another class ation, Compos‐ interfaces do
ition
Inheritance
Polymo Same thing is done in different ways Using compile-
rphism time and run-time Aggreg‐ When one class contains a reference Loosely coupled
polymorphism ation of another class classes
Abstract When a class has one or more Used: When default Run- Also called overriding. When child-classes over-write
Class unimplemented methods, it implementation is time method implementations of parent-class.
should be declared abstract. needed for some
The sub-classes should provide methods, and specific static keyword
implementation for the unimpl‐ implementations for static Shared by all members of the class. It can be accessed
emented methods, else they other methods based field before objects are created
should also be declared abstract on the class implem‐
static Can be accessed without creating an instance of the class.
enting them
method They can only access static variables and static methods.
Cannot access this or super
cheatography.com/evanescesn09/
Core Java Cheat Sheet
by evanescesn09 via cheatography.com/88543/cs/20288/
final
It is best to store passwords as char[ ] because if passwords are
fields treated as constants stored as Strings, the string tends to be in the JVM pool even after
methods cannot be overridden by child classes all references to it no longer exist. This causes a vulnerability in the
system. In case of Char[ ], once all the references to char[ ] are
classes cannot be inherited
gone, the Java Garbage Collector deletes the char[ ] to preserve
memory. So, it's safer.
finalize( )
StringBuilder, StringBuffer
finalize() method is a protected and non-static method of java.l‐
StringBuilder To create mutable strings in Java
ang.Object class. This method will be available in all objects you
StringBuffer To create thread-safe mutable strings in Java
create in java. This method is used to perform some final operations
or clean up operations on an object before it is removed from the
String methods
memory
s.charAt(int index)
String Creation s.compareTo(s2), s.compareToIgnoreCase(s2)
Literal : Creates Strings in String pool, in JVM. Multiple strings s.concat(s2)
String s can have same value. Only one copy of the word exists
s.contains(sequence of characters)
="" in the String pool, and the references of it are updated.
s.equals(s2), s.equalsIgnoreCase(s2)
Object: Creates a string object in heap. The heap in-turn checks
s.length()
String s the JVM String Pool to see if there exists a string with
= new same value. s.replace(character, replacement) )
String( ); s.replaceAll(character, replacement)
cheatography.com/evanescesn09/
Core Java Cheat Sheet
by evanescesn09 via cheatography.com/88543/cs/20288/
s.append(s2)
s.deleteCharAt(int index)
s.indexOf(string ), s.indexOf(string, fromIndex)
s.insert(int index, objectValue)
s.replace(int startIndex, int endIndex, String)
s.reverse( )
s.toString( )
s.trimToSize( )
s.setCharAt(int index, charSequence)
cheatography.com/evanescesn09/
Sorting Cheat Sheet
by evanescesn09 via cheatography.com/88543/cs/20303/
Sorting is rearranging the given data in a Time O(nlogn) - logn to sort half the Technique
specific format- ascending or descending. Complexity data in each recursion, n to Best Used only for small set of data, it
The purpose of sorting elements is to merge all the input data to doesn't scale well for larger
greatly improve the efficiency of searching give the final sorted output data sets
while doing computations on the data. Space O(n) extra space required How? Find min value in the list,
In Java, we can sort primitive data (using Complexity when merging back the swap it with element at
sorting algorithms) , or user-defined data sorted data current index. Repeat the
(using Comparable or Comparator interf‐
Merge Sort does not preserve ordering or process till the list is sorted.
aces)
elements of the same value Time O(n^2)
We have 2 main kinds of sorting:
Complexity
1. Internal Sorting - done in main memory Insertion Sort
Space O(1) - because it is done in
2. External Sorting - algorithms that use
Technique Complexity place
external memory like tape, or a disk for
sorting. Best used for small data
Heap Sort
External sorting is used when data is too Advantages Preserves insertion order of
large to fit into main memory. elements of same values Technique Divide and Conquer
cheatography.com/evanescesn09/
Design Patterns: Observer, Interpreter, Memento Cheat Sheet
by ppesq via cheatography.com/20490/cs/3257/
one-to-many dependency between subject and provides the ability to restore an object to its Represent the grammar of a language with a
observers, so that when subject changes, the previous state hierarchical object-oriented design.
observers are notified and updated.
a memento is like a magic cookie that The language is usually a domain specific
a way of notifying change to a number of encapsulates a checkpoint capability language.
classes
Questions Questions
Questions
What problem does it solve? What problem does it solve?
What is it?
you want to save the state of an object so A language must be parsed and
many objects need to be notified of changes that you can restore it later. interpreted.
in the state of one object
Where have I seen it before? Where have I seen it before?
Where have I seen it before? Git or any version control system for that Parsers
RSS feeds or any pub/sub system you might matter. A memento makes rollbacks
have used/coded possible.
Ok, this is cool. What do I need to
implement it?
Ok, this is cool. What do I need to Ok, this is cool. What do I need to
implement it? implement it?
Example
Example Example
A programmer (caretaker) asks for a copy
A referee (concrete subject) notifies all the A roman numeral (context) is converted into
(memento) of the code (originator) he/she is
players and commentators (concrete decimal notation by the parser (Abstract
modifying. Later he/she decides he doesn't like
observers) about changes in the state of a Expression).
the new state of the code so he restores it with
Soccer match. Each player must be notifiable. Derivation: LIV => 50 + IV => 50 + (-1 + 5) =>
the copy it still has.
50 + 4 => 54
Advantages Disadvantages
Observer: minimal coupling; easy addition and Observer: Possible memory leak; Objects
removal of observers might need to work hard to deduce what
changed in the subject.
Memento: it is an encapsulated copy so it
avoids exposing its info; the storage burden is Memento: Copy operation to a memento can
on the caretaker, not on originator be costly for the originator; Caretaker might
have large storage costs.
Interpreter: easy to
change/extend/implement/evaluate a language Interpreter: Complex grammars are hard to
maintain and debug.
See
http://docs.oracle.com/javase/6/docs/api/java/util/
ArrayList.html for more.
m.put(key, value) Inserts value with key ! x (not) x && y (and) x || y (or)
See s = MessageFormat.format(
public boolean groupSum(int start, public <T extends Person> T set (T element)
int[] nums, int target) { {...}
<T>: Bedingungen für Input
if (start >= nums.length) return
T : Rückgabetyp
(target == 0);
Wildcard-Typ (Nutzen: Typargument nicht
if (groupSum(start + 1, nums,
relevant)
target - nums[start])) return
true; Node<?> undef --> kein Lesen & schreiben
ausser: Object o = undef.getValue();
schwarze Pfeile: expliziet if (groupSum(start + 1, nums,
rote Pfeile: impliziet, evt Genauigkeitsverlust target)) return true;
Lambdas
alles andere impliziet return false;}
Collection<String> (p1, p2) -> p1.getAge() –
Switch-Statement validParentheses(int nofPairs){ p2.getAge()
1); people.sort(Comparator.comparing(p1
Wenn Ausdruck Wert1 entspricht, wird
for (String infix : infixes)
Anweisung 1 ausgeführt... -> p1.getLastName().length()));
{
Syntax: (Parameter) -> {Body}
Typ Polymorphismus for (String suffix :
suffixes) {
car extends vehicle StreamAPI
list.add("(" + infix +
@Override people
")" + suffix);}}}}
drive(){}
return list;} .stream()
Vehicle v = new Car();
.filter(p -> p.getAge() >= 18)
//calls drive of Car not Vehicle
Generics .map(p -> p.getLastName())
v.drive();
.sorted()
allg. Form
Klasse hat eigenen Typ plus alle Typen der .forEach(System.out::println);
class Pair<T,U>
Superklassen. people.stream().mapToInt(p ->
verschiedene "Brillen" TypeBound (Bedingungen für Type) p.getAge())
Dynamic Dispatch = dynamischer Typ zur class Node<T extends Comparable<T>> .average().ifPresent(System.out::pr
Laufzeit entscheidet über aufgerufene Node<Person>//ok Node<Student>//Error intln);
Methoden.
Multiple TypeBounds (mit & anhängen) Map<String, Integer>
class Node<T extends Person & totalAgeByCity =
Comparable<Person>>
generische Methode
serialisiert alle direkt & inderekt referenz. Obj (a+b).equals(c); I. Methode mit Rumpf: default void
//false report(){...}
a + b == c; interface I1 extends I2,I3
class C2 extends C1 implements I1,
String Literals gepoolt. True Fälle --> es
werden keine neuen Objekte erstellt I2
Integer-Pooling -128 bis 127 wenn I1&I2 nun gleiche Methoden haben
(signatur) --> C2 muss ine der beiden
Collections überschreiben. Zugriff möglich mit
I1.super.methode();
Array int[] intArray = new int[3];
I2.super.methode();
List List<T> al = new
ArrayList<>();
{} interface Comparator<T> {
super(message);} } }
@Before RegEx
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 überschreiben!
` x.equals(y) → x.hashCode() == y.hashCode()
Grund: inkonsistenz bei Hashing. obj wird nicht
gefunden, obwohl in Hash-Tabelle,
x.contains(y) --> nutzt hashCode() & equals()