Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
static modifier matters!
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 5) |
Lecture notes |
Pdf slides |
|
(#2 of 5) |
Lecture notes |
Pdf slides |
|
(#3 of 5) |
Lecture notes |
Pdf slides |
|
(#4 of 5) |
Lecture notes |
Pdf slides |
|
(#5 of 5) |
Lecture notes |
Pdf slides |
|
new operator: Creating rectangle
instances
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
nullLecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
importLecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 3) |
Lecture notes |
Pdf slides |
|
(#2 of 3) |
Lecture notes |
Pdf slides |
|
(#3 of 3) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 3) |
Lecture notes |
Pdf slides |
|
(#2 of 3) |
Lecture notes |
Pdf slides |
|
(#3 of 3) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
scale(...) method
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 3) |
Lecture notes |
Pdf slides |
|
(#2 of 3) |
Lecture notes |
Pdf slides |
|
(#3 of 3) |
getPerimeter() method
implementation
Lecture notes |
Pdf slides |
|
Rectangle.getPerimeter()Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
private modifier access violation
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Circle and variable scopes
Lecture notes |
Pdf slides |
|
(#1 of 3) |
Circle and variable scopes
Lecture notes |
Pdf slides |
|
(#2 of 3) |
Circle and variable scopes
Lecture notes |
Pdf slides |
|
(#3 of 3) |
Documenting classes and methodsLecture notes |
Pdf slides |
|
Generated JavadocLecture notes |
Pdf slides |
|
(#1 of 5) |
Generated JavadocLecture notes |
Pdf slides |
|
(#2 of 5) |
Generated JavadocLecture notes |
Pdf slides |
|
(#3 of 5) |
Generated JavadocLecture notes |
Pdf slides |
|
(#4 of 5) |
Generated JavadocLecture notes |
Pdf slides |
|
(#5 of 5) |
Refactoring «r» ⇒ «radius»Lecture notes |
Pdf slides |
|
(#1 of 3) |
Refactoring «r» ⇒ «radius»Lecture notes |
Pdf slides |
|
(#2 of 3) |
Refactoring «r» ⇒ «radius»Lecture notes |
Pdf slides |
|
(#3 of 3) |
Scope assignment problemLecture notes |
Pdf slides |
|
this overriding method
scope
Lecture notes |
Pdf slides |
|
(#1 of 5) |
this overriding method
scope
Lecture notes |
Pdf slides |
|
(#2 of 5) |
this overriding method
scope
Lecture notes |
Pdf slides |
|
(#3 of 5) |
this overriding method
scope
Lecture notes |
Pdf slides |
|
(#4 of 5) |
this overriding method
scope
Lecture notes |
Pdf slides |
|
(#5 of 5) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 11) |
Lecture notes |
Pdf slides |
|
(#2 of 11) |
Lecture notes |
Pdf slides |
|
(#3 of 11) |
Lecture notes |
Pdf slides |
|
(#4 of 11) |
Lecture notes |
Pdf slides |
|
(#5 of 11) |
Lecture notes |
Pdf slides |
|
(#6 of 11) |
Lecture notes |
Pdf slides |
|
(#7 of 11) |
Lecture notes |
Pdf slides |
|
(#8 of 11) |
Lecture notes |
Pdf slides |
|
(#9 of 11) |
Lecture notes |
Pdf slides |
|
(#10 of 11) |
Lecture notes |
Pdf slides |
|
(#11 of 11) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
IO.print(ln)Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 6) |
Lecture notes |
Pdf slides |
|
(#2 of 6) |
Lecture notes |
Pdf slides |
|
(#3 of 6) |
Lecture notes |
Pdf slides |
|
(#4 of 6) |
Lecture notes |
Pdf slides |
|
(#5 of 6) |
Lecture notes |
Pdf slides |
|
(#6 of 6) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 3) |
Lecture notes |
Pdf slides |
|
(#2 of 3) |
Lecture notes |
Pdf slides |
|
(#3 of 3) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
common-1.0.jarLecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 5) |
Lecture notes |
Pdf slides |
|
(#2 of 5) |
Lecture notes |
Pdf slides |
|
(#3 of 5) |
Lecture notes |
Pdf slides |
|
(#4 of 5) |
Lecture notes |
Pdf slides |
|
(#5 of 5) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
second-0.9.jarLecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
javadoc:javadocLecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 3) |
Lecture notes |
Pdf slides |
|
(#2 of 3) |
Lecture notes |
Pdf slides |
|
(#3 of 3) |
Lecture notes |
Pdf slides |
|
pom.xml content changes
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 8) |
Lecture notes |
Pdf slides |
|
(#2 of 8) |
Lecture notes |
Pdf slides |
|
(#3 of 8) |
Lecture notes |
Pdf slides |
|
(#4 of 8) |
Lecture notes |
Pdf slides |
|
(#5 of 8) |
Lecture notes |
Pdf slides |
|
(#6 of 8) |
Lecture notes |
Pdf slides |
|
(#7 of 8) |
Lecture notes |
Pdf slides |
|
(#8 of 8) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 8) |
Lecture notes |
Pdf slides |
|
(#2 of 8) |
Lecture notes |
Pdf slides |
|
(#3 of 8) |
Lecture notes |
Pdf slides |
|
(#4 of 8) |
Lecture notes |
Pdf slides |
|
(#5 of 8) |
Lecture notes |
Pdf slides |
|
(#6 of 8) |
Lecture notes |
Pdf slides |
|
(#7 of 8) |
Lecture notes |
Pdf slides |
|
(#8 of 8) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 13) |
Lecture notes |
Pdf slides |
|
(#2 of 13) |
Lecture notes |
Pdf slides |
|
(#3 of 13) |
Lecture notes |
Pdf slides |
|
(#4 of 13) |
Lecture notes |
Pdf slides |
|
(#5 of 13) |
Lecture notes |
Pdf slides |
|
(#6 of 13) |
Lecture notes |
Pdf slides |
|
(#7 of 13) |
Lecture notes |
Pdf slides |
|
(#8 of 13) |
Lecture notes |
Pdf slides |
|
(#9 of 13) |
Lecture notes |
Pdf slides |
|
(#10 of 13) |
Lecture notes |
Pdf slides |
|
(#11 of 13) |
Lecture notes |
Pdf slides |
|
(#12 of 13) |
Lecture notes |
Pdf slides |
|
(#13 of 13) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
float / double !!
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
@Test
annotation
Lecture notes |
Pdf slides |
|
Assertions
class
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 4) |
Lecture notes |
Pdf slides |
|
(#2 of 4) |
Lecture notes |
Pdf slides |
|
(#3 of 4) |
Lecture notes |
Pdf slides |
|
(#4 of 4) |
Lecture notes |
Pdf slides |
|
(#1 of 5) |
Lecture notes |
Pdf slides |
|
(#2 of 5) |
Lecture notes |
Pdf slides |
|
(#3 of 5) |
Lecture notes |
Pdf slides |
|
(#4 of 5) |
Lecture notes |
Pdf slides |
|
(#5 of 5) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 7) |
Lecture notes |
Pdf slides |
|
(#2 of 7) |
Lecture notes |
Pdf slides |
|
(#3 of 7) |
Lecture notes |
Pdf slides |
|
(#4 of 7) |
Lecture notes |
Pdf slides |
|
(#5 of 7) |
Lecture notes |
Pdf slides |
|
(#6 of 7) |
Lecture notes |
Pdf slides |
|
(#7 of 7) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 6) |
Lecture notes |
Pdf slides |
|
(#2 of 6) |
Lecture notes |
Pdf slides |
|
(#3 of 6) |
Lecture notes |
Pdf slides |
|
(#4 of 6) |
Lecture notes |
Pdf slides |
|
(#5 of 6) |
Lecture notes |
Pdf slides |
|
(#6 of 6) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 7) |
Lecture notes |
Pdf slides |
|
(#2 of 7) |
Lecture notes |
Pdf slides |
|
(#3 of 7) |
Lecture notes |
Pdf slides |
|
(#4 of 7) |
Lecture notes |
Pdf slides |
|
(#5 of 7) |
Lecture notes |
Pdf slides |
|
(#6 of 7) |
Lecture notes |
Pdf slides |
|
(#7 of 7) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 6) |
Lecture notes |
Pdf slides |
|
(#2 of 6) |
Lecture notes |
Pdf slides |
|
(#3 of 6) |
Lecture notes |
Pdf slides |
|
(#4 of 6) |
Lecture notes |
Pdf slides |
|
(#5 of 6) |
Lecture notes |
Pdf slides |
|
(#6 of 6) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 5) |
Lecture notes |
Pdf slides |
|
(#2 of 5) |
Lecture notes |
Pdf slides |
|
(#3 of 5) |
Lecture notes |
Pdf slides |
|
(#4 of 5) |
Lecture notes |
Pdf slides |
|
(#5 of 5) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 12) |
Lecture notes |
Pdf slides |
|
(#2 of 12) |
Lecture notes |
Pdf slides |
|
(#3 of 12) |
Lecture notes |
Pdf slides |
|
(#4 of 12) |
Lecture notes |
Pdf slides |
|
(#5 of 12) |
Lecture notes |
Pdf slides |
|
(#6 of 12) |
Lecture notes |
Pdf slides |
|
(#7 of 12) |
Lecture notes |
Pdf slides |
|
(#8 of 12) |
Lecture notes |
Pdf slides |
|
(#9 of 12) |
Lecture notes |
Pdf slides |
|
(#10 of 12) |
Lecture notes |
Pdf slides |
|
(#11 of 12) |
Lecture notes |
Pdf slides |
|
(#12 of 12) |
Lecture notes |
Pdf slides |
|
int argument
Lecture notes |
Pdf slides |
|
int arguments by
overloading
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Arrays.copyOf()Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
static void main(String[]
args)Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Creating executable jarLecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 7) |
Lecture notes |
Pdf slides |
|
(#2 of 7) |
Lecture notes |
Pdf slides |
|
(#3 of 7) |
Lecture notes |
Pdf slides |
|
(#4 of 7) |
Lecture notes |
Pdf slides |
|
(#5 of 7) |
Lecture notes |
Pdf slides |
|
(#6 of 7) |
Lecture notes |
Pdf slides |
|
(#7 of 7) |
Lecture notes |
Pdf slides |
|
(#1 of 12) |
Lecture notes |
Pdf slides |
|
(#2 of 12) |
Lecture notes |
Pdf slides |
|
(#3 of 12) |
Lecture notes |
Pdf slides |
|
(#4 of 12) |
Lecture notes |
Pdf slides |
|
(#5 of 12) |
Lecture notes |
Pdf slides |
|
(#6 of 12) |
Lecture notes |
Pdf slides |
|
(#7 of 12) |
Lecture notes |
Pdf slides |
|
(#8 of 12) |
Lecture notes |
Pdf slides |
|
(#9 of 12) |
Lecture notes |
Pdf slides |
|
(#10 of 12) |
Lecture notes |
Pdf slides |
|
(#11 of 12) |
Lecture notes |
Pdf slides |
|
(#12 of 12) |
Lecture notes |
Pdf slides |
|
(#1 of 9) |
Lecture notes |
Pdf slides |
|
(#2 of 9) |
Lecture notes |
Pdf slides |
|
(#3 of 9) |
Lecture notes |
Pdf slides |
|
(#4 of 9) |
Lecture notes |
Pdf slides |
|
(#5 of 9) |
Lecture notes |
Pdf slides |
|
(#6 of 9) |
Lecture notes |
Pdf slides |
|
(#7 of 9) |
Lecture notes |
Pdf slides |
|
(#8 of 9) |
Lecture notes |
Pdf slides |
|
(#9 of 9) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
int
representation
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
switch no longer works
Lecture notes |
Pdf slides |
|
getPrice()Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
private
Day constructor
Lecture notes |
Pdf slides |
|
Day instance
creation
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
enum Day
replacing public class DayLecture notes |
Pdf slides |
|
switch statements working
again
Lecture notes |
Pdf slides |
|
enum constructor being implicitly
privateLecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
The sum of 2 and 5 is 7 |
Method's return type: Method's arguments: Method returns Method expects two int values arguments of type int ↘ ↙ ↙ static int sum ( int a, int b) { int result = a + b; return result; } ↖ Returning a value of type int
static void main() {
...
// Compile error: Non-static method 'sum(int, int)'
// cannot be called from a static context
int result = sum (i,j);
...
}
// No static modifier
int sum ( int a, int b) {
return a + b;
}/**
* Calculates the sum of two integers.
*
* @param a the first integer to add
* @param b the second integer to add
* @return the sum of the two integers
*/
static int sum (int a, int b) {
int result = a + b;
return result;
}| Method definition | Method usage |
|---|---|
public class Helper { static int sum(int a, int b) { int result = a + b; return result; } } |
public class Add {
static void main() {
int i = 2, j = 5;
int result = Helper.sum(i, j);
IO.println("The sum of " + i +
" and " + j + " is " + result);
}
} |
The concept of classes: Blueprints for objects.
UML diagram visualization.
Classes and related instances.
The «new» operator.
Assignment of attribute values. Working with «null».
In object oriented languages classes:
are blueprints for objects.
contain attributes and methods.
allow for implementation hiding.
allow for tailored access to methods and attributes.
|
|
|
|
|
Rectangle dashedRectangle = new Rectangle();
Rectangle solidRectangle = new Rectangle();
...new class-name ([argument 1[, argument 2] ...] )
“Create an instance of class
Rectangle”.
“Create a Rectangle
object.”
“Create a
Rectangle”.
Rectangle dashedRectangle = new Rectangle();
dashedRectangle.width = 28;
dashedRectangle.height = 10;
dashedRectangle.hasSolidBorder = false;Syntax accessing object attributes:
variable.attributeName = value; |
Exception in thread "main" java.lang.NullPointerException
at de.hdm_stuttgart.mi.classdemo.App.main(App.java:17) |
Rectangle r;
... // possible object assignment to variable r.
if (null == r) {
IO.println("No rectangle on offer");
} else {
IO.println("Width:" + r.width);
}Significance for larger projects.
Fully qualified vs. «import».
java.lang and other exceptions.
Grouping of related classes (e.g. subsystems).
Structuring big systems.
Provide access restrictions using:
public, private
and protected modifier
Resolving class name clashes. Example:
java.lang.String vs. my.personal.String
Package names below java. are reserved.
Package names should not start with javax. either.
Package names must not contain operators:
mi.hdm-stuttgart.de
→ de.hdm_stuttgart.mi.
Packages should start with reversed DNS avoiding clashes.
Fully qualified class name:
java.util.Scanner ❶ scanner = // Clumsy and new java.util.Scanner ❷(System.in); // redundant
Using import :
import java.util.Scanner; ❶ public class Q { static void main() { Scanner ❷ scanner = new Scanner ❷(System.in); ... } }
| Bad | Good |
|---|---|
import java.util.*; public class Q { static void main() { Scanner s = new Scanner(System.in); Date today = new Date(); } } |
import java.util.Scanner; import java.util.Date; public class Q { static void main() { Scanner s = new Scanner(System.in); Date today = new Date(); } } |
import java.lang.String; ❶ // Optional import java.util.Scanner;❷ // Required public class Q { static void main() { String message = "Hello!"; Scanner ❸ s = new Scanner(System.in); } }

![]() |
|
Object behaviour, state transitions, derived values.
Selected examples both of state-changing and state-conserving methods.
Rectangle sample methods.
Example: Calculate a rectangle's area.
Example: Scale a rectangle.
Scale a rectangle and calculate its new perimeter.
public class Rectangle {
int width, height;
int getArea() {
return width * height;
}
} |
static void main() {
Rectangle r = new Rectangle();
r.width = 20;
r.height = 30;
int area = r.getArea();
IO.println(
"Area of rectangle is: " + area);
} |
Area of rectangle is: 600
public class Rectangle {
int width, height;
int getArea() {...}
public void scale (int factor) {
width *= factor;
height *= factor;
}
} |
Rectangle r = new Rectangle();
r.width = 20;
r.height = 30;
IO.println("Area before scaling: "
+ r.getArea());
r.scale(2);
IO.println("Area after scaling: "
+ r.getArea()); |
Area before scaling: 600 Area after scaling: 2400
|
width=66 height=44 |
|
|
|
Perimeter=110 |
Justifying access restrictions.
public, protected «package local»
and private.
Best practices.
Fine-grained control on attributes and methods.
Support encapsulation / Information hiding.
Purpose: Hide implementation details within class or package
public class DayTime {
private int ❶ minutesSinceMidnight;
public int getMinute() { ❷
return minutesSinceMidnight % 60;
}
public int getHour() {❷
return minutesSinceMidnight / 60;
}
} |
public class DayTime {
private int minute, hour;❶
public int getMinute() { ❷
return minute;
}
public int getHour() { ❷
return hour;
}
} |
No access to private field of alien
class Time:
public class Q {
static void main() {
DayTime t = new DayTime();
// Error: 'minutesSinceMidnight' has private access in 'Time'
t.minutesSinceMidnight = 371;
}
}No access modifier = package - local access
package a; public class X{ // No public // modifier int i; } |
package a; public class Y { void displayValues(X x) { // o.K. IO.println(x.i); } } |
package b; // X resides in different package import a.X; public class Z { void displayValues(X x) { // Error: // 'i' is not public in 'a.X' // Cannot be accessed from // outside package IO.println(x.i); } } |
| Access Level | Other package | Child class | Same package | Same class |
public |
yes | yes | yes | yes |
protected |
no | yes | yes | yes |
| [omitted] | no | no | yes | yes |
private |
no | no | no | yes |
Use the most restrictive access level that makes sense for a particular member.
Use private unless you have a
good reason not to.
Avoid public fields except for
constants. Public fields tend linking to a particular
implementation and limit your flexibility in changing your
code.
| Direct access | Setter access |
|---|---|
public class Time {
public int hour, minute;
} |
public class Time {
private int hour, minute;
public void setTime(int h, int m) {
minute = m;
hour = h;
}
} |
Allow for change of implementation.
Allow for non business - logic concerns. Examples:
Logging
Adding persistence (Databases)
public class Time {
private int hour, minute;
public void setTime(int h, int m) {
minute = m;
hour = h;
IO.println("Time has been set to " + hour + ":" + minute);
}
}| Direct access | Setter / getter access |
|---|---|
final Time time = new Time();
// To be changed at multiple
// project locations
time.minute = 17 * 60 + 45; |
final Time time = new Time()
time.setTime(17, 45); |
Type signatures.
Method signatures: Prerequisite understanding method overloading.
boolean ❶ startsWith(String prefix, int toffset) ❷
| Method | Return type | Argument type list |
|---|---|---|
void print() |
void | (void) |
int add (int a, int b) |
int | (int, int) |
int max (int a, int b) |
int | (int, int) |
void print (int a, float b) |
void | (int, float) |
void display (float a, int b) |
void | (float, int) |
boolean startsWith❶(String prefix, int toffset) ❷
| Method | Method name | Method signature |
|---|---|---|
void print() |
(void) | |
int add (int a, int b) |
add | (int, int) |
int max (int a, int b) |
max | (int, int) |
void print (int a, float b) |
(int, float) | |
void display(float a, int b) |
display | (float, int) |
Same name, different argument types.
«C» programming language comparison.
Common examples.
|
|
No argument int value 33 double value 4.333 Two int values -1 and 7 |
Static polymorphism.
Compile time binding.
Early binding.
#include <stdio.h>
void print() {
printf("No argument\n");
}
void print(int i) { /* Error: redefinition of ‘print’ */
printf("int value %d\n", i);
}
void main(void) {
print();
print(33);
}Code in file print.c |
Compile / execute |
|---|---|
|
Compiling > cc -o print print.c |
|
Executing file
> ./print No argument int value 33 |
public class Person {
String getDetails() { return "dummy";}
int getDetails() { return 1;} // Error: 'getDetails()' is already
} // defined in 'Person'| Return type | Method signature | |
|---|---|---|
| Method name | Argument type list | |
| String | getDetails | (void) |
| int | getDetails | (void) |
Only method signature support in Java™ ignoring return type.
In Java™ method signatures allow for uniquely addressing a method within a given class e.g.:
The method named print having an
int argument followed by a double:
print(int, double)Combined instance creation and initialization.
Constructors are methods, but ...
Constructor overloading and a class' default constructor.
|
|
|
Combining statements desired: |
|
|---|---|
|
// how to ???
Rectangle r = new Rectangle(28, 10, false); |
public class Rectangle {
int width, height;
boolean hasSolidBorder;
...
public ❶ Rectangle ❷ (int width, int height, boolean hasSolidBorder){
this.width = width;
this.height = height;
this.hasSolidBorder = hasSolidBorder;
}
}[access modifier] constructorName (listOfArguments) {
[constructor body]
}Default constructor e.g. obj = new
MyClass().
Non-default constructor e.g. :
obj = new String("xyz");Can only be executed on object creation.
Are being called prior to any non-constructor method.
Only one of potentially multiple constructors will be executed exactly one time.
However nesting is possible.
|
|
public class Rectangle {
int width, height;
┏━▶ public Rectangle(int width,
┃ int height){
┃ this.width = width;
┃ this.height = height;
┃ }
┃ public Rectangle() {
┣━◀━━ this(1, 1); ❶
┃ }
┃ public Rectangle(
┃ int widthAndHeight) {
┗━◀━━ this(widthAndHeight, ❷
widthAndHeight);
}
} |
|
|
Equivalent: Rectangle r =
new Rectangle(); |
|
|---|---|
|
|
|
|
|
Class, method and block scopes.
Documentation, «good» variable names and the this
keyword.
/** Representing circles.
*/
public class Circle {
private double radius;
/** Creating a circle.
* @param r representing the circle's radius
*/
public Circle(double r) {
radius = r;
}
public double getDiameter() {
return 2 * radius;
}
}/** Representing circles.
*/
public class Circle {
private double radius;
/** Creating a circle.
* @param radius Circle's size
*/
public Circle(double radius) {
radius = radius; // Warning: Variable 'radius' is assigned to itself.
}
public double getDiameter() {
return 2 * radius;
}
}Motivating class attributes and methods.
Example: A club and its affiliated members.
Syntax of static and employment
considerations
|
final Helper instance = new Helper(); // Why do we need an instance just for // computing the maximum of two values? IO.println("Maximum: " + instance.maximum(-3, 5)); |
Maximum: 5 |
Observation: The instance's state is irrelevant for finding the maximum of two values.
Each club member has got a name.
Each member has got an ascending unique membership number.
The overall club's member count needs to be accounted for.
Solution:
Class level: Advance club's member count by each new member.
Instance level: New members receive name and current member count plus 1.
public class ClubMember {
final private String name;
public ClubMember(final String name) {
this.name = name;
}
public String toString() {
return "Member " + name;
}
} |
Member John Member Karen |
public class ClubMember {
static ❶ private int memberCount = 0;
final private int memberNumber; ❷
final private String name;
public ClubMember(final String name) {
this.name = name;
memberNumber = ++memberCount; ❸
}
public String toString() {
return "Member " + name + ", member number " + memberNumber ❹;
}
}final ClubMember
john = new ClubMember("John"),
karen = new ClubMember("Karen");
IO.println(john); ❶ // toString() is being
IO.println(karen); // called implicitly |
Member John, member number 1 Member Karen, member number 2 |
public class ClubMember {
static private int memberCount = 0;
...
public ClubMember(final String name) {
this.name = name;
memberNumber = ++memberCount;
}
static public int getMemberCount() ❶ {
return memberCount; ❷
}
...
} |
Member Karen, member number 2 Club's member count:3 |
{class name}.{variableName}
{class name}.{methodName}([parameter])
public class X {
int a; ❶
static int b; ❷
❶ ❷ ❸ IO.print(...)
|
Class variable (static) out of type
|
|
|
One of 9 overloaded
methods in class |
for, while and do ... whileCross project dependencies.
Repositories and project artifacts.
Automated third-party class import and dependency management
Executing automated tests
Complete project lifecycle:
compile, test, execute, package, deploy
Extensible plugin architecture
Source: CreatePdf.java |
PDF output |
import com.itextpdf.kernel.pdf.PdfDocument; ... final PdfWriter writer = new PdfWriter("helloWorld.pdf"); final PdfDocument pdf = new PdfDocument(writer); final Document document = new Document(pdf, PageSize.A8.rotate()); document.add(new Paragraph("Hello World!"). setFontColor(ColorConstants.MAGENTA). setFontSize(20)); document.close(); |
|
![]() |
|
mvn dependency:tree
...
--- dependency:3.6.1:tree (default-cli) @ hellopdf ---
de.hdm_stuttgart.mi:hellopdf:jar:0.9
\- com.itextpdf:itext-core:pom:8.0.2:compile
+- com.itextpdf:barcodes:jar:8.0.2:compile
| \- org.slf4j:slf4j-api:jar:1.7.36:compile
+- com.itextpdf:font-asian:jar:8.0.2:compile
+- com.itextpdf:forms:jar:8.0.2:compile
+- com.itextpdf:hyph:jar:8.0.2:compile
+- com.itextpdf:io:jar:8.0.2:compile
| \- com.itextpdf:commons:jar:8.0.2:compile
+- com.itextpdf:kernel:jar:8.0.2:compile ...
mvn archetype:generate [INFO] Scanning for projects... ... 1: remote -> am.ik.archetype:elm-spring-boot-blank-archetype ... 2: remote -> am.ik.archetype:graalvm-blank-archetype ... 3: remote -> am.ik.archetype:graalvm-springmvc-blank-archetype ... ... 2083: remote -> org.apache.maven.archetypes:maven-archetype-quickstart... ... 3330: remote -> za.co.absa.hyperdrive:component-archetype_2.12 (-) Choose a number or apply filter ... |
Helper.java |
pom.xml |
|---|---|
package de.hdm_stuttgart.common; public class Helper { static public long factorial(int n) { long result = 1; for (int i = 2; i <= n; i++) { result *= i; } return result; } } |
<project xmlns="http://maven.apache.org...> ... <groupId>de.hdm-stuttgart</groupId> <artifactId>common</artifactId> <version>1.0</version> ... </project> |
goik@goiki Helper> mvn install
...
[INFO] Building common 1.0
...
[INFO] Installing .../target/common-1.0.jar to
/home/goik/.m2/repository/de/hdm-stuttgart/common/1.0/common-1.0.jargoik@goiki tmp> unzip .../de/hdm-stuttgart/common/1.0/common-1.0.jar Archive: /home/goik/.m2/repository/de/hdm-stuttgart/common/1.0/common-1.0.jar ... creating: de/ creating: de/hdm-stuttgart/ creating: de/hdm-stuttgart/common/ inflating: de/hdm-stuttgart/common/Helper.class creating: META-INF/maven/ creating: META-INF/maven/de.hdm-stuttgart/ creating: META-INF/maven/de.hdm-stuttgart/common/ inflating: META-INF/maven/de.hdm-stuttgart/common/pom.xml inflating: META-INF/maven/de.hdm-stuttgart/common/pom.properties ... inflating: org/apache/logging/log4j/core/AbstractLifeCycle.class ...
<project ...> ... <groupId>de.hdm-stuttgart</groupId> <artifactId>lottery</artifactId> <version>0.9</version> <dependencies> <dependency> <groupId>de.hdm-stuttgart</groupId> <artifactId>common</artifactId> <version>1.0</version> </dependency> ... </project>
static public long binomial(int n, int k) {
return (Helper.factorial(n) / Helper.factorial(k)
/ Helper.factorial(n - k));
}
static void main() {
IO.println("There are " + binomial(5, 2) +
" ways to draw 2 out of 5 numbers");
IO.println("There are " + binomial(49, 6) +
" ways to draw 6 out of 49 numbers");
}Download file mavenTemplate.zip from
here.
Extract mavenTemplate.zip to folder
template.
Optional: Edit template/pom.xml
reflecting your project needs i.e. <groupId> and related.
Optional: Import your project in Intellij IDEA.
> mvn --batch-mode -e archetype:generate \
-DgroupId=de.hdm_stuttgart.mi.sd1 -DartifactId=second -Dversion=0.9 \
-DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4
[INFO] Scanning for projects...
...
[INFO] BUILD SUCCESS ...See artifact reference.
> mvn --batch-mode -e archetype:generate \ -DgroupId=de.hdm_stuttgart.mi.sd1 -DartifactId=second -Dversion=0.9 \ -DarchetypeGroupId=de.hdm_stuttgart.mi -DarchetypeArtifactId=mi-maven-archetype-quickstart -DarchetypeVersion=2.5 [INFO] Error stacktraces are turned on. [INFO] Scanning for projects... ... [INFO] BUILD SUCCESS ...
> mvn --batch-mode ❶ -e archetype:generate ❷ \ \ -DarchetypeGroupId=de.hdm_stuttgart.mi \ ❸ -DarchetypeArtifactId=mi-maven-archetype-quickstart \ -DarchetypeVersion=2.5 \ \ -DgroupId=de.hdm_stuttgart.mi.sd1 ❹ \ -DartifactId=second \ -Dversion=0.9
> tree -a ├── dependency-reduced-pom.xml ├── .gitignore ├── pom.xml ❶ ├── Readme.md └── src ├── main │ ├── java │ │ └── de │ │ └── hdm_stuttgart │ │ └── mi │ │ └── sd1 │ │ ├── App.java ❷ │ │ ├── HighlightSample.java │ │ └── Statistics.java │ └── resources │ └── log4j2.xml └── test └── java └── de └── hdm_stuttgart └── mi └── sd1 └── AppTest.java
> mvn compile [INFO] Scanning for projects... ... [INFO] Building second 0.9 ... [INFO] Changes detected - recompiling the module! [INFO] Compiling 1 source file to /ma/goik/second/target/classes [INFO] -------------------------------------------------------- [INFO] BUILD SUCCESS
> tree target/classes target/classes/ ├── de │ └── hdm_stuttgart │ └── mi │ └── sd1 │ ├── App.class │ ├── HighlightSample.class │ └── Statistics.class └── log4j2.xml
> mvn package [INFO] -------------------< de.hdm_stuttgart.mi.sd1:second >------------------- [INFO] Building second 0.9 ... [INFO] ------------------------------------------------------- [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] Running de.hdm_stuttgart.mi.sd1.AppTest [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.253 s -- in de.hdm_stuttgart.mi.sd1.AppTest ... [INFO] Building jar: /home/goik/Downloads/second/target/second-0.9.jar ... [INFO] BUILD SUCCESS
> java -jar target/second-0.9.jar
Hi there, let's have
fun learning Java!
2026-01-11 07:40:33,903 INFO [main] sd1.App (App.java:27) - The following two statements will log to file A1.log, ...
2026-01-11 07:40:33,905 DEBUG [main] sd1.App (App.java:28) - You may configure 'src/main/resources/log4j2.xml'
2026-01-11 07:40:33,905 DEBUG [main] sd1.App (App.java:29) - for adapting both console and 'A1.log' file outputRemark: This will execute App.class being
contained in second-0.9.jar.
> mvn javadoc:javadoc [INFO] Scanning for projects... ... Generating /ma/goik/second/target/site/apidocs/allclasses-noframe.html... Generating /ma/goik/second/target/site/apidocs/index.html... Generating /ma/goik/second/target/site/apidocs/overview-summary.html... Generating /ma/goik/second/target/site/apidocs/help-doc.html...
See e.g. class String documentation.
> mvn clean ... [INFO] [INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ second --- [INFO] Deleting /ma/goik/second/target [INFO] ------------------------------------------------------------------------ [
Built in Maven support in Intellij IDEA.
MI supplementary archetypes require MI archetype configuration in
~/.m2/settings.xml.

Your Maven project depends on its
pom.xml file.
Reloading changed pom.xml file.
Test categories.
Why unit testing? Idea of test «driven development».
Required steps.
Unit test: Test individual methods, classes and packages in isolation.
Integration Test: Test a group of associated components/classes.
Acceptance / Functional Test: Operate on a fully integrated system, testing against the user interface.
Regression Test: Ensure system integrity after (implementation) change.
Load test: Responsiveness vs. system load.
Informal problem specification:
A prime number is a whole number greater than 1 whose only factors are 1 and itself.
Sample values: 2, 3, 5, 7, 11, 13, 17, 23, ...
First write tests, then implement.
Specify but not yet implement classes / methods.
Write skeleton (dummy) implementations.
Write corresponding unit tests.
Implement skeleton.
Test your implementation.
Providing both an implementation and related tests possibly revealing coding flaws.
Providing prime number related tests.
/**
* Identifying prime numbers.
*/
public class Prime {
/**
* Check whether a given integer candidate is prime or not ❶
* @param candidate A positive integer value
* @return true if and only if candidate is a prime number.
*/
public static boolean isPrime(int candidate) {
return true ❷; //TODO: Dummy value to be implemented correctly
}
}| Code | |
|---|---|
| Result | 1 is a prime number 2 is a prime number 3 is a prime number 4 is a prime number 5 is a prime number ... |
| Input | Expected output | Input | Expected output |
|---|---|---|---|
1 |
false |
7 |
true |
2 |
true |
8 |
false |
3 |
true |
9 |
false |
4 |
false |
10 |
false |
5 |
true |
11 |
true |
6 |
false |
12 |
false |
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class PrimeTest { @Test ❶ public void testIsNotPrime() { ❷ Assertions.assertFalse(Prime.isPrime(1)); } @Test ❶ public void testIsPrime() { Assertions.assertTrue(Prime.isPrime(2)); } void someOrdinaryMethod() ❸ {...} ...
|
A |
|
|
The See Assertions for details. |
|
|
Any methods not being annotated by |
goik@goiki Prime_v01> mvn test ... [INFO] ------------------------------------------------------- [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] Running de.hdm_stuttgart.mi.sd1.PrimeTest [ERROR] Tests run: 5, Failures: 3, Errors: 0, Skipped: 0, Time elapsed: 0.063 s <<< FAILURE! -- in de.hdm_stuttgart.mi.sd1.PrimeTest [ERROR] de.hdm_stuttgart.mi.sd1.PrimeTest.testOddNonPrimes -- Time elapsed: 0.030 s <<< FAILURE! org.opentest4j.AssertionFailedError: expected: <false> but was: <true> at org.junit.jupiter.api.AssertionFailureBuilder.build(AssertionFailureBuilder.java:158) ...
| Code | @Test public void testIsNotPrime() {
Assertions.assertFalse(Prime.isPrime(1), "1 is no prime number");
}
@Test public void testIsPrime() {
Assertions.assertTrue(Prime.isPrime(2), "2 is a prime number");
} |
|---|---|
| Result | org.opentest4j.AssertionFailedError: 1 is no prime number ==>
Expected :false
Actual :true |
@Test public void test_Primes() { Assertions.assertTrue(Prime.isPrime(3)); Assertions.assertTrue(Prime.isPrime(5)); Assertions.assertTrue(Prime.isPrime(7)); Assertions.assertTrue(Prime.isPrime(11)); ... } @Test public void testOddNonPrimes() { Assertions.assertFalse(Prime.isPrime(9)); Assertions.assertFalse(Prime.isPrime(15)); Assertions.assertFalse(Prime.isPrime(21)); ...}
@Test public void testEvenNonPrimes() { for (int i = 2; i < 100; i++) { Assertions.assertFalse(Prime.isPrime(2 * i)); } }
public static boolean isPrime(int candidate) { for (int i = 2; i < candidate; i++) { if (0 == candidate % i) { // i divides value return false; } } return candidate != 1; }
goik@goiki Prime_v01> mvn test ... [INFO] ------------------------------------------------------- [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] Running de.hdm_stuttgart.mi.sd1.PrimeTest [INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.047 s -- in de.hdm_stuttgart.mi.sd1.PrimeTest [INFO] [INFO] Results: [INFO] [INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------
Try improving the algorithm.
Introducing an error.
101 / 2 = 50 remainder 1 101 / 3 = 33 remainder 2 101 / 4 = 25 remainder 1 101 / 5 = 20 remainder 1 101 / 6 = 16 remainder 5 101 / 7 = 14 remainder 3 101 / 8 = 12 remainder 5 101 / 9 = 11 remainder 2 101 / 10 = 10 remainder 1 101 / 11 = 9 remainder 2 101 / 12 = 8 remainder 5 101 / 13 = 7 remainder 10 ...
Big performance gain:
public static boolean isPrime(int candidate) {
for (int i = 2; i * i < candidate; i++) {
if (0 == candidate % i) {
return false;
}
}
return candidate != 1;
}public static boolean isPrime(int candidate) { //for (int i = 2; i * i < candidate; i++) { for (int i = 2; i * i <= candidate; i++) { if (0 == candidate % i) { return false; } } return candidate != 1; }
Separate both test parameters and expected values from code.
Provide parameter values either by variables or by separate CSV files.
Read Parameterized Classes and Tests for details.
| Hard-coded | public void testPrimes() { Assertions.assertEquals(false, Prime.isPrime(1)); Assertions.assertEquals(true, Prime.isPrime(2)); Assertions.assertEquals(true, Prime.isPrime(3)); Assertions.assertEquals(false, Prime.isPrime(4));} |
|---|---|
| Parameterized | @ParameterizedTest @CsvSource( textBlock = """ false, 1 true, 2 true, 3 false, 4""") public void testPrimes(boolean expected, int primeCandidate) { Assertions.assertEquals(expected, Prime.isPrime(primeCandidate)); } |
mvn test ─ de.hdm_stuttgart.mi.sd1.PrimeTest - 0.098 s
├─ ✔ testPrimes(int, boolean)[1] 1, false - 0.035 s
├─ ✔ testPrimes(int, boolean)[2] 2, true - 0.001 s
├─ ✔ testPrimes(int, boolean)[3] 3, true - 0.001 s
└─ ✔ testPrimes(int, boolean)[4] 4, false - 0.001 s@ParameterizedTest @CsvFileSource(resources = "/primes.csv") public void testPrimesByFile (boolean expected, int primeCandidate, ) { Assertions.assertEquals( expected ,Prime.isPrime(primeCandidate) ); } |
File test/resources/primes.csv: false, 1 true, 2 true, 3 false, 4 |
mvn test ─ de.hdm_stuttgart.mi.sd1.PrimeTest - 0.098 s
├─ ✔ testPrimesByFile(int, boolean)[1] false, 1 - 0.031 s
├─ ✔ testPrimesByFile(int, boolean)[2] true, 2 - 0.001 s
├─ ✔ testPrimesByFile(int, boolean)[3] true, 3 - 0.001 s
└─ ✔ testPrimesByFile(int, boolean)[4] false, 4 - 0.001 sSelected assertion methods.
Considerations when comparing float and
double values.

org.opentest4j.AssertionFailedError: expected: <3.6> but was: <3.5999999999999996>
...
at de.hdm_stuttgart.AppTest.test1_3(AppTest.java:35)IO.println("3.6 - 3 * 1.2 == " + (3.6 - 3 * 1.2));Result:
3.6 - 3 * 1.2 == 4.440892098500626E-16
public class doubleCompareTest {
static final double delta = 1E-15;
/**
* Comparing 3.6 and 3 * 1.2 within delta's limit
*/
@Test
public void test1_3() {
Assertions.assertEquals(3.6, 3 * 1.2 , delta);
}
}public @interface @Test { ... } |
|
public class Assertions { public static void assertTrue(boolean condition, String message) { ... } public static void assertEquals(long expected, long actual) { ... } ... }
<project ...>
...
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>6.0.2</version>
<scope>test</scope>
</dependency>
...
</dependencies>
...
</project>Local: /home/goik/.m2/repository/org/junit/jupiter/junit-jupiter-api/6.0.2/junit-jupiter-api-6.0.2.jar
Remote: https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api
> jar -tf junit-jupiter-api-6.0.2.jar
META-INF/
META-INF/MANIFEST.MF
...
org/
org/junit/
org/junit/jupiter
org/junit/jupiter/api
...
org/junit/jupiter/api/Assertions.class
...Primitive and value types revisited.
|
|
|
|
Array or class instances i.e. String,
java.util.Scanner etc.
| Value type | |
a=5 b=1 |
| Reference type | |
r=Joe Simpson s=Joe Simpson |
static void main() {
int value = 300;
sub(value);
IO.println("value = " + value);
}
static void sub(int n) {
n = 1000;
IO.println("n = " + n);
} |
n = 1000 value = 300 |
|
Before duplicateString: My After duplicateString: MyMy |
|
Before duplicateString: My After duplicateString: My |
int a = 1;
int &b = a;
cout << a << " : " << b << endl;
a = 5;
cout << a << " : " << b << endl; |
1 : 1 5 : 5 |
// Passing a reference // to variable n void printDuplicateValue(int& n) { n = 2 * n; cout << "duplicateValue: " << n << endl; } int main() { int value = 3; cout << "Before call: " << value << endl; printDuplicateValue(value); cout << "After call: " << value << endl; } |
Before call: 3 duplicateValue: 6 After call: 6 |
Combining array allocation and value assignment:
|
|
...println(" String: " + "".getClass().getTypeName());
...println(" int[]: " + new int[]{}.getClass().getTypeName());
...println(" double[]: " + new double[]{}.getClass().getTypeName());
...println(" boolean[]: " + new boolean[]{}.getClass().getTypeName());
...println("StringBuffer[]: " + new StringBuffer[]{}.getClass().getTypeName()); String: java.lang.String
int[]: int[]
double[]: double[]
boolean[]: boolean[]
String[]: java.lang.String[]
StringBuffer[]: java.lang.StringBuffer[]static void main() {
final int [] lectures = new int[3]; // Three lectures
fill(lectures, 25); // Default lecture having 25 participants
IO.println("Second lecture has got " + lectures[1] +
" participants");
}
/**
* Initialize array with default value.
*
* @param values Array to be initialized.
* @param common New value for all array elements.
*/
static void fill(final int[] values, final int common) {
for (int i = 0; i < values.length; i++) {
values[i] = common;
}
}Second lecture has got 25 participants
// Value type
final boolean values[] = {true, true, false, true};
// Reference type
final String shapes[] = {"Triangle", "Circle"};| Code | |
|---|---|
| Result | Winner: 34 |
| Code | |
|---|---|
| Result | Winner: 34 Winner: 31 7 Winner: 2 8 5 |
Similar code in multiply overloaded methods.
Tedious: Each added argument requires adding another method.
Objective: Get rid of boilerplate code!
| Code | |
|---|---|
| Result | Winner: 1 2 3 4 5 6 7 8 9 |
| Code | |
|---|---|
| Result | Winner: 1 2 3 4 5 6 7 8 9 Winner: 20 19 18 17 16 15 |
Only one varargs parameter per method.
Must be a method's last argument.
The varargs section in chapter 4 of [Kurniawan].
java.util.Arrays
helpers
Sorting and searching arrays.
Fill in values.
Compare array contents.
final String[] names = {"Eve", "Aaron", "Paul", "Mandy"};
IO.println(" toString: " + Arrays.toString(names));
Arrays.sort(names);
IO.println("sort|toString: " + Arrays.toString(names));Result:
toString: [Eve, Aaron, Paul, Mandy] sort|toString: [Aaron, Eve, Mandy, Paul]
final String[] names = {"Aaron", "Eve", "Mandy", "Paul"};
// Precondition: Array must be ordered!
...println("sort|find(Mand): " + Arrays.binarySearch(names, "Mand"));
...println("sort|find(Mandy): " + Arrays.binarySearch(names, "Mandy"));
...println("sort|find(Mandyer): " + Arrays.binarySearch(names, "Mandyer"));Result:
sort|find(Mand): -3 sort|find(Mandy): 2 sort|find(Mandyer): -4
final String[] names =
{"Eve", "Aaron", "Paul", "Mandy"};
IO.println("toString: " +
Arrays.toString(names));
Arrays.fill(names, "N.N");
IO.println("toString: " +
Arrays.toString(names)); |
toString: [Eve, Aaron, Paul, Mandy] toString: [N.N, N.N, N.N, N.N] |
final String[] names = {"Eve", "Aaron", "Paul", "Mandy"};
final String[] lastTwoNames = Arrays.copyOfRange(names, 2, 6);
IO.println("toString: " + Arrays.toString(lastTwoNames));Result:
toString: [Paul, Mandy, null, null]
final String[]
l1 = {new String("Eve"), new String("Aaron"),
new String("Paul"), new String("Mandy")},
l2 = {new String("Eve"), new String("Aaron"),
new String("Paul"), new String("Mandy")},
l3 = {new String("Eve"), new String("Aaron"),
new String("Paul"), new String("Mobile")};
IO.println("l1.equals(l2):" + Arrays.equals(l1, l2));
IO.println("l1.equals(l3):" + Arrays.equals(l1, l3));Result:
l1.equals(l2):true l1.equals(l3):false
Dealing with fixed size.
final String[] member = {"Eve", "John", "Peter", "Jill"};
final String newCourseMember = "Ernest";
member.length = 5; // Error: Size unchangeable
member[4] = newCourseMember;static void main() {
❶ String[] member = {"Eve", "John", "Peter", "Jill"};
final String newMember = "Ernest";
member ❷= append(member, newMember);
}
static String[] append (final String[] values, final String newValue) {
final String[] copy = ❸ new String[values.length + 1];
for (int i = 0; i < values.length; i++) { ❹
copy[i] = values[i]; ❺
}
copy[copy.length - 1] = newValue; ❻
return copy;
}final String[] member = {"Eve", "John", "Peter", "Jill"};
IO.println("Original array: " + Arrays.toString(member));
final String newMember = "Ernest";
member = append(member, newMember);
IO.println("Extended array: " + Arrays.toString(member));Original array: [Eve, John, Peter, Jill]
Extended array: [Eve, John, Peter, Jill, Ernest]static void main() {
final int [] start = {1,7,-4},
added = append(start, 77);
IO.println("added: " + Arrays.toString(added));
}
static public int[] append(final int[] values, final int newValue) {
final int[] result = Arrays.copyOf(values, values.length + 1);
result[values.length] = newValue;
return result;}Result:
added: [1, 7, -4, 77]
static int main(String[]
args)main(...) and its array
argument.
Implementing parameter passing.
package myapp;
public class Cmd {
static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
IO.println("Parameter " + (i + 1) + ": " + args[i]);
}
}
}java myapp.Cmd 21 334 -13 Parameter 1: 21 Parameter 2: 334 Parameter 3: -13

|
❶ |
Entry class |
|
❷ |
Parameters |

<artifactId>maven-shade-plugin</artifactId>
...
<transformer ...>
<manifestEntries>
<Main-Class>myapp.Cmd</Main-Class>
</manifestEntries>... |
unzip ww-1.0-SNAPSHOT.jar
cat tmp/META-INF/MANIFEST.MF
...
Created-By: Apache Maven 3.5.0
Build-Jdk: 1.8.0_151
Main-Class: myapp.Cmd |
mvn package ... java -jar target/ww-1.0-SNAPSHOT.jar 21 334 -13 Parameter 1: 21 Parameter 2: 334 Parameter 3: -13
Method calls, behind the scenes.
Stack and heap memory.
Stack frames and value propagation. Using the debugger.
public class Circle {
static final double
PI = 3.141592653589793;
double r;
/** Change a circle's area
* @param area The desired new area
* @return The circle's new radius */
double setArea(final double area ❶) {
double val ❷ = area / PI ❸;
return ❹ r ❺ = Math.sqrt(val);
}
} |
|||||
|
|
Class scope (static)
|
Application process |
| Instance scope | Object lifetime: new
(...) until being garbage collected.
|
| Method scope | Method invocation until return.
|
Allocation of class or array instances:
|
|
De-allocation subject to garbage collection.
One instance per process thread.
Hosting variables (values or references)

enum)
Modeling finite sets of discrete states.
Examples:
A room's door: {OPEN, CLOSED}
State of matter: {SOLID, LIQUID,
GASEOUS}
No dynamic change of state set.
enum)
Example: Weekdays Monday till Sunday represented by constant
int values.
Common pitfall examples.
Insufficient means of language protection against self - inflicted problems.
public class Lecture { public final int dayHeld; /* e.g. to be held on Tuesdays */ public final String title; /* e.g. «PHP introduction» */ public Lecture(final int dayHeld, final String title) { this.dayHeld = dayHeld; this.title = title; } }
Quick and dirty:
Class Driver: final Lecture phpIntro = new Lecture(1 /* Monday */, "PHP introduction"), advancedJava = new Lecture(5 /* Friday */, "Advanced Java");
Error prone:
Weeks start on Mondays?
Index starts with 0 or 1?
public class Day { static public final int MONDAY = 1, TUESDAY = 2, WEDNESDAY = 3, THURSDAY = 4, FRIDAY = 5, SATURDAY = 6, SUNDAY = 7; }
Class Driver: final Lecture phpIntro = new Lecture(Day.MONDAY, "PHP introduction"), advancedJava = new Lecture(Day.FRIDAY, "Advanced Java");
public class Day { ... public static String getDaysName(final int day) { switch (day) { case MONDAY: return "Monday"; case TUESDAY: return "Tuesday"; case WEDNESDAY: return "Wednesday"; case THURSDAY: return "Thursday"; case FRIDAY: return "Friday"; case SATURDAY: return "Saturday"; case SUNDAY: return "Sunday"; default: return "Illegal day's code: " + day; } } }
public class Lecture { public final int dayHeld; ... public String toString() { return "Lecture «" + title + "» being held each " + Day.getDaysName(dayHeld); } }
// Class Driver final Lecture phpIntro = new Lecture( Day.MONDAY, "PHP introduction"), advancedJava = new Lecture( Day.FRIDAY, "Advanced Java"); IO.println(phpIntro); IO.println(advancedJava); |
Lecture «PHP introduction» being held each Monday Lecture «Advanced Java» being held each Friday |
// Class Screwed final Lecture phpIntro = new Lecture(99, "PHP introduction"); IO.println(phpIntro); |
Lecture «PHP introduction» being
held each Illegal day's code: 99Bad: Not even a compiler warning message! |
/** * Charge double prices on weekends * @param day Day of week * @param amount Product costs * @return the effective amount for * given day of week. */ static public int getPrice( final int day, final int amount) { switch (day) { case Day.SATURDAY: case Day.SUNDAY: return 2 * amount; default: return amount; } } |
// Correct IO.println( getPrice(Day.SUNDAY, 2)); // Argument mismatch IO.println( getPrice(2, Day.SUNDAY)); 4 7 Bad: Not even a compiler warning message! |
enum)
Representing enumeration values by instances gaining type safety.
Partial problem solution.
Roadmap:
Define a dedicated enumeration representing class.
Create exactly one class instance per enumeration value.
Enumeration value equality comparison by virtue of the
== operator.
public class Day { static public final Day MONDAY = new Day(), TUESDAY = new Day(), WEDNESDAY = new Day(), THURSDAY = new Day(), FRIDAY = new Day(), SATURDAY = new Day(), SUNDAY = new Day(); }
Note: Class without instance attributes.
Reverting to if .. else if ... required 🙄
public static String getDaysName(final Day day) { if (MONDAY == day) { // Switch no longer possible, sigh! return "Monday"; } else if (TUESDAY == day) { ... } else if (SUNDAY == day) { return "Sunday"; } else { return "Illegal day instance: " + day; } }
/** * Charge double prices on weekends * @param day Day of week * @param amount Product costs * @return the effective amount for given day of week. */ static public int getPrice(final Day day, final int amount) { if (Day.SATURDAY == day || Day.SUNDAY == day) { return 2 * amount; } else { return amount; }}
IO.println(Screwed2.getPrice(Day.SUNDAY, 2)); // Class Driver, o.K. IO.println(Screwed2.getPrice(2, Day.SUNDAY)); // Argument mismatch, compile time error
Class Screwed: final Day PAST_SUNDAY = new Day(); final Lecture phpIntro = new Lecture( PAST_SUNDAY, "PHP introduction"); IO.println(phpIntro.toString()); |
Lecture «PHP introduction» being
held each Illegal day instance:
de.hdm_stuttgart.mi.sd1.
class_wrapper.Day@63961c42 |
enum)
Clearing the mess.
Sad: switch still not working.
public class Day { // Disallow object creation outside class private Day() {} static public final Day MONDAY = new Day(), TUESDAY = new Day(), ... SUNDAY = new Day(); }
Class Screwed: Day PAST_SUNDAY = new Day(); Lecture phpIntro = new Lecture( PAST_SUNDAY, "PHP introduction"); IO.println(phpIntro.toString()); |
Compile time error: 'Day()' has private access in
'de.hdm_stuttgart.mi.sd1.
class_wrapper_private.Day' |
public class Day { static public final Day MONDAY = new Day("Monday"), ... SUNDAY = new Day("Sunday"); public final String name; private Day(final String name) { this.name = name; } public String toString() { return name; } }
enum)
enum replacing classIntroducing enum as kind of restricted
class.
Makes switch working again!
public class Day { static public final Day MONDAY = new Day("Monday"), ... SUNDAY = new Day("Sunday"); public final String name; private Day(final String name) { this.name = name; } public String toString() { return name; } } |
public enum Day { MONDAY("Monday"), ... SUNDAY("Sunday"); final String name; Day(final String name) { this.name = name; } public String toString() { return name;} } |
public enum Day { ... public static String getItalianDayName(final Day day) { switch (day) { case MONDAY: return "Lunedì"; case TUESDAY: return "Martedì"; ... case SUNDAY: return "Domenica"; } return null; // Actually unreachable, but static compiler code analysis is limited } }
public enum Day {
...
private Day(final String name)
{ ... |
Compile time warning: Modifier 'private' is redundant for |
public enum Day {
...
public Day(final String name)
{ ... |
Compile time error: Modifier 'public' not allowed here |
Prohibits enum external instance creation.