Professional Documents
Culture Documents
Java Cheat Sheet
Java Cheat Sheet
Class
-abstract blueprints
-objects
-state/ attribtues
-behaviour/methods
Variables:
Declare a variable: <<data type>> <<identifier>>;
Initialize a variable: <<identifier>> = <<value>>;
Define a variable: <<data type>> <<identifier>> = <<value>>;
Assign a value: <<identifier>> = <<value>>;
Order of Execution:
Right side of an assignment is always evaluated first
The result is assigned to the left side
Expressions
Everything that can be resolved to a value
- a variable: course
- a calculation: 18 + 24
- a methode, which can be evaluated to a value (with return)
Always be careful when using double and other floating point data types
Class
class Detective{
}
Instatiation-
Object instantiation: <<class name>> <<identifier>> = new <<class name>>();
Detective ourDetective = new Detective();
→ Definition of a variables, → identifier and we assigne an actual object with the new operator
Method
Method Declaration (without return value): void <<methodIdentifier>>(){
//code here
}
Methods can only be called within other methods or to define the value of attributes.
class Detective{
String name = "Duke";
}
Define an attribute (including an initial value):
<<data type>> <<identifier>> = <<value>>;
lass Detective{
String name;
String lastname;
void sayName(){
System.out.println(name + " " + lastname);
}
}
Within the class class in which the attributes are defined or declared attributes can be accessed by
using the attribute identifier.
Attributes define the state of an object. Attributes are declared and defined in a class.
Attributes and variables are very similar concepts. The difference is that variables can only
live within a method, while attributes are valid throughout the class or its objects and can
be shared between all methods of a class or object.
Generally, attributes are not shared among all instances of a class. Each instance (or
object) of a class has its own set of values for its attributes.
boolean
if condition
if (<<condition>>){
//code block executed if codition is true
} else {
//executed if condition is false
}
Week 2
Arrays
<<data type>>[] <<arrayIdentifier>>;
1 → String[] cases;
2 → cases = new String[5];
(1) Declaration: let the program know that we will need an array of
Strings and give it an identifier
(2) Initialization: allocate the memory for an array of five Strings
Initialization with new initializes all elements of an array with the data type‘s default value
Zusammenziehen: → Declaration and initialization can be done at the same time:
String[] cases = new String[5];
String[] cases = {"Meeting Eike", "Potsdam Underground", "A Strange Phone", "Hijacked: Paco the
Parrot", "The Museum Mystery"};
Loops
□ Count-controlled loop: for (from x to y, e.g. count y times)
□ Condition-controlled loop:
while (as long as x is true, do y)
- check condition then execute statement
do while (do y as long as x is true)
-execute statement then check condition
- statements in body are always executed at least once
Collection-controlled loop
Count-controlled loop:
keyword (<<initialization expression>>; <<termination expression>>; expression>>)
for (int i = 0; i < 3; i++){
}
bad practice, but to clarify
int i = 0;
while ( i < 3 ){
// Functionality of for-loop
// written as a while-loop terminate when loop count
i++;}
Condition-controlled loop
while ( <<conditional expression>> ){
// Condition-controlled loop
}
Arrays + Loops
for( int i = 0; i < cases.length; i++){
System.out.println(cases[i]);
}
Parameters
String hello = concat("Hello", "Duke", ":::");
System.out.println(hello);
[...]
String concat(String p1, String p2, String connector){
return p1 + " " + connector + " " + p2;
}
Scope
Defines the "zone of validity" of a variable
The variable can only be accessed (read/write) within that zone
■ Defined/delimited by {} e.g. in
□ Class
□ Method
□ Control structure (condition/loop)
way in via paramteres, way out via return statements
->
not working (weil Paramter in curly braces defininiert und nicht accesible)
if (x == 5) {
int z = 12;
} else {
z = 18;
}
ok:
int z;
if (x == 5) {
z = 12;
} else {
z = 18;
}
Constructor
class Robot{
String color;
Robot(){
color = "blue";
}
}
■ The constructor is a method with some special features:
□ Initializes attributes
□ Same identifier as its class
□ No explicit return type – it returns the newly created object
□ It can take any number of parameters (including zero)
■ Calling the constructor: Robot robby = new Robot();
Constructor with parameter
class Robot{
String color;
Robot(String color){
this.color = color;
}
}
□ If the parameter has the same identifier than the attribute, this is used to clearly distinguish the
local parameter from the attribute
□ this always refers to the current object
■ Calling the constructor: Robot robby = new Robot("blue");
multiple parameteser: Robot robby = new Robot("blue", 2);
Overloading construtors
Overloading constructors is only possible when
□ the amount of parameters – or –
□ the types of the parameters differ
Robot(String color, int numberOfEyes) { ... }
Robot(){ ... }
Robot(int numberOfEyes){ ... }
Robot(String color){ ... }
this. this()
this.<<attributeIdentifier>>
■ Access attributes of the current object
■ Implicitly set as long as there is no naming conflict
this(<<argumentList>>);
■ Call overloaded constructor
■ Set initial state of the current object
class Robot{
String color;
int numberOfEyes;
Robot(String color, int numberOfEyes){
this.color = color;
this.numberOfEyes = numberOfEyes;
}
Robot(){
this("blue", 2);
}
Robot(String color){
this(color, 2);
}
Robot(int numberOfEyes){
this("blue", numberOfEyes);
}
}
Every method can be overloaded. (just in the same class).
■ Constructors are a typical use case for method overloading
■ In all other cases, think twice about method overloading → Is it really the same method or does it
do something different?
null
Placeholder for non-existing objects
■ Test whether a value is null with == (equality operator)
■ Test whether a value is not null with != (inequality operator)
Exeptions
Etwas mit null machen wollen …
Exception in thread "main"
java.lang.NullPointerException
Exception Type
at ExceptionExamples.npe(ExceptionExamples.java:7)
Class - Method Filename Line
at ExceptionExamples(ExceptionExamples.java:3)
where method npe() was called
try {
// could potentially raise an exception
} catch (<<ExceptionType>> e) {
// recover from exception
}