Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Java

Class
-abstract blueprints
-objects
-state/ attribtues
-behaviour/methods

The state of an object influences its behavior.


The behavior of an object influences its state.

Variables:
Declare a variable: <<data type>> <<identifier>>;
Initialize a variable: <<identifier>> = <<value>>;
Define a variable: <<data type>> <<identifier>> = <<value>>;
Assign a value: <<identifier>> = <<value>>;

Variables Have Data Types


Plus Operator (+):
Addition for ints
Concatenation for Strings

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)

Operation Short form


Addition +=
Subtraction -=
Multiplication *=
Division /=
Increment by 1 ++
Decrement by 1 –

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
}

Method Call: <<method identifier>>();

1. Program starts in main()


2. Instantiation of Object duke
3. Call speak() on Object duke (Instance of class Detective)

Method Call (with dot-operator):


<<object identifier>>.<<method identifier>>();

Methods can only be called within other methods or to define the value of attributes.

Access Attribute Value:


<<object identifier>>.<<attribute identifier>>;
Set Attribute Value:
<<object identifier>>.<<attribute identifier>> = <<value>>;

Attributes can either be declared or defined.


Assignments of values (and initializations) always have to happen within a method.
Defintion works in a class as well:

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.

<<return data type>> <<method identifier>>(){


//some source code here
return <<return value>>;
}

boolean

Syntax: boolean <<identifier>> = true; // or false

Do not use == to compare Objects.


boolean result = duke.equals(ann);

Control structures allow us to execute code


□ only under certain conditions (branches)
□ repeatedly, depending on conditions (loops)

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;
}

Method Header/ Signature


Defines the public interface of a method.
Components
□ Identifier
□ Return type
□ Amount and type of expected parameters

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)

Data types Default values


(Attributes)
int 0
double 0.0
char '\u0000'
boolean false
String null
All Objects null
If attributes are not initialized by the developer, Java provides them with a default value
(Local) variables do not have default values!

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

zu viele Elemente in Array →


Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 2
at ExceptionExamples.arrayMagic(ExceptionExamples.java:7)

Exception in thread "main" java.lang.Error: Unresolved


compilation problem:
Type mismatch: cannot convert from String to int
at ExceptionExamples.type (…)

Exception in thread "main" java.lang.Error:


Unresolved compilation problem:
The local variable name may not have been initialized

try {
// could potentially raise an exception
} catch (<<ExceptionType>> e) {
// recover from exception
}

nested Loop, Image


for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++){
System.out.print(image[y][x]+" ");
}
}
continue, break, return

You might also like