[Link].
cz
Java
Jan Kožusznik, David Ježek
[Link]@[Link]
Tel: 597 325 874
Room: EA406
06.10.202 Java 1 2
5
Literature
●
SCHILDT, Herbert, 2022. Java: A Beginner’s Guide, Ninth Edition. 9 edition. New
York: McGraw-Hill Education. ISBN 978-1260463552.
●
[Link] Java™ Tutorials. accessed September 29, 2022,[Link]
/javase/tutorial/[Link]
●
[Link] Java™ SE API. accessed September 29, 2022, [Link]
/javase/17/docs/api/[Link]
●
BLOCH, Joshua, 2018. Effective Java. 3 edition. Boston: Addison-Wesley
Professional. ISBN 978-0-13-468599-1.
●
SCHILDT, Herbert, 2021. Java: The Complete Reference, Twelfth Edition. 12
edition. New York: McGraw-Hill Education. ISBN 978-1260463415.
●
BARNES. Objects First with Java: A Practical Introduction Using BlueJ, Global
Edition. 6th edition. Boston: Pearson, 2016. ISBN 978-1-292-15904-1.
06.10.2025 Java 1 3
1th lecture - objectives
●
Motivation for Java ●
Comparing variables
●
Features of Java ●
Structure of classes,
●
Tools enumerations
●
Basic structure of Java program
●
Java control structures
●
Types, operators,
●
Arrays
●
Objects
●
Methods with a variation
number of arguments
●
Variables
06.10.2025 Java 1 4
Motivation for Java
Motto:
„Write once, run anywhere“
Sun Microsystem
[Link]
06.10.202 Java 1 5
5
Java Technology
●
Java is the global standard for developing and delivering embedded
and mobile applications, games, web-based content, and enterprise
software.
●
Java enables you to efficiently develop, deploy, and use exciting
applications and services.
●
From laptops to data centers, game consoles to scientific
supercomputers, cell phones to the Internet, Java is everywhere!
06.10.2025 Java 1 6
Tiobe Index
[Link]
06.10.2025 Java 1 7
The Story of Java
●
In 1990, Sun Microsystems began a research project to extend the
power of network computing to consumer devices, such as video
cassette recorders (VCRs) and televisions.
●
The belief was that the next wave in computing was the union of
digital consumer devices and computers.
●
There were also frustrations with the use of the C/C++ language at
Sun.
06.10.2025 Java 1 8
The Story of Java
●
The Green Team, a team of highly
skilled software developers at Sun
under the leadership of James
Gosling, developed Java (originally
called Oak) as their solution.
●
Devices with different central
processing units (CPUs) could be
connected and share the same
software enhancements through a
single programming language.
06.10.2025 Java 1 9
Java Version History
06.10.2025 Java 1 10
Java Version History - continues
Java Version Date Java Version Date
Java SE 9 September 2017 Java SE 21 (LTS) 2023-09-19
Java SE 10 March 2018 Java SE 22 2024-03-19
Java SE 11 (LTS) September 2018 Java SE 23 2024-09-17
Java SE 12 March 2019 …
… Java SE 25 (LTS) September 2025
Java SE 17 (LTS) September 2021
…
06.10.2025 Java 1 11
Features of Java technology
●
Multiplatform and portable
●
Object Oriented
●
It has simple language – core is API
●
Robust, Dynamic and Secure
●
Multithreaded
●
Support for distributed application
06.10.2025 Java 1 12
Translate High-level Code to Machine Code
06.10.2025 Java 1 13
Linked to Platform-Specific Libraries
06.10.2025 Java 1 14
Platform-Dependent Programs
06.10.2025 Java 1 15
Java Is Platform-Independent
06.10.2025 Java 1 16
Java Programs Run in a JVM
06.10.2025 Java 1 17
Mobile Phones
●
Languages supported for Android development by Google:
– Java
– C++
– Kotlin – JVM based language
06.10.2025 Java 1 18
Java is (not only) language
06.10.2025 Java 1 19
Java Technologies
●
Java SE ●
Java Card
●
Jakarta EE ●
Java DB (Apache Derby open
●
Java ME source database)
●
Java ME Embeded
●
GraalVM
●
Java TV
●
Java on OCI
06.10.2025 Java 1 20
Used Tools
06.10.202 Java 1 21
5
Java Runtime Environment (JRE)
●
Includes:
– The Java Virtual Machine (JVM)
– Java class libraries
●
Purpose:
– Read bytecode (.class)
– Run the same bytecode
anywhere with a JVM
06.10.2025 Java 1 22
Java Development Kit (JDK)
●
Includes:
– JRE
– Java Compiler
– Additional Tools
●
Purpose:
– Compile bytecode
(.java→.class)
06.10.2025 Java 1 23
Integrated Development Environment (IDE)
●
Purpose: ●
Examples:
– Provide a sophisticated text – Eclipse
editor – IntelliJ
– Offer assistance debugging code – Netbeans
– Manage projects – Greenfoot and BlueJ
– Write source code (.java)
06.10.2025 Java 1 24
Introduction to Java Program Structure
06.10.202 Java 1 25
5
Application running
package [Link].java1; ●
In folder:
public class Launcher { cz→vsb→fei→java1
public static void main(String[]
args) {
[Link]("Hello!!!");
●
Source code in file:
}
}
[Link]
From command line:
●
compiling
javac [Link] //produces [Link]
●
running
java –cp {path-to-your-compiled-classes} Launcher
06.10.2025 Java 1 26
Class – Basic Compilation Unit
●
Source file: ●
compiler (program javac ) -
public class MySuperiorClass { contained in JDK
// class definition
// ...
}
●
JVM (program java) - contained ●
[Link] binary
in JRE file contains Java byte code
06.10.2025 Java 1 27
Types in Java
06.10.202 Java 1 28
5
Data Types
●
Primitive types – only values:
– int is in [-2147483648, 2147483647 ]
– double is in [4.9*10-324, 1.7976931348623157*10308]
– boolean is in {false, true}
●
Object types – reference to instance of class:
– type from Java (more than 18000) – e.g. String
– defined by user – e.g. Rectangle, Person
06.10.2025 Java 1 29
Primitive Types
●
Similar to C/C++ but:
– Types has exactly same size on every platforms
– All numeric types are signed
– boolean type is separate type and numeric types are not automatically converted in.
– Type for strings (String) is object type
●
Integer data types:
– byte (8b), short (16b), int (32b), long (64b)
●
Their literals should contain ‘_’ …. 10_000
●
long literals are defined with suffix l … 10l
●
Floating point (Real) data type
– float (32b), double (64b)
●
float literals are defined with suffix f … 3.151f
●
Textual primitive type - char (16 b) – only single 16 bit Unicode character (0-65535)
●
Boolean type – boolean (1b)
06.10.2025 Java 1 30
Operators
●
Mainly for primitive types – exception is ‘+’ used for string Operators Precedence
concatenation and ‘[]’ used for arrays.
postfix expr++ expr--
●
Like C:
unary ++expr --expr +expr -expr ~ !
– Unary: +,-,++,--,~,!
multiplicative */%
– Binary: +,-,*,/,%, modulo % also available for double
– assignment: =, +=,-=, … additive +-
– relational: ==, !=, <=, … operands are values of some shift << >> >>>
numeric type (integer or real) result is value of boolean relational < > <= >= instanceof
type.
– logical: !, ||, && ,^ - operands and result are always equality == !=
values of boolean type bitwise AND &
●
available also non lazy version |, & - both operands are
always evaluated bitwise exclusive OR ^
– ternary: <condition expression>?<value1>:<value2> bitwise inclusive OR |
– bitwise: logical AND &&
– cast: () – automatic casting of value is allowed to a type logical OR ||
that has bigger range(numeric primitive) or to parents
(object) ternary ?:
●
Construct expression with defined precedence. assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
06.10.2025 Java 1 31
Object Type
●
An Object is an distinguishable entity that has:
– Identity: a uniqueness which distinguishes it from all other objects
– Behavior: services it provides to another objects
– State: value of attributes held by an object
●
A class is an abstraction of objects with similar implementation
– Class is definition of set of similar objects
– Every object is an instance of one class
06.10.2025 Java 1 32
Object is an instance of a class
●
Memory is allocated, object is created and reference to the instance
is stored into variable.
Instance of class
Rectangle is created.
Rectangle rectangle1 = new Rectangle(); //an object creation
Identifiers - name variables, functions, classes, and objects -
anything that programmers need to identify and use. Identifiers
start with letter, underscore or dollar sign and they are
case-sensitive. More about convention:
[Link]
06.10.2025 Java 1 33
Object responds to a message call
●
Methods are called on object only by ‘.’ (not by -> )
[Link]();
Message on the instance
could be sent.
06.10.2025 Java 1 34
Attributes
●
State of an object is Rectangle Rectangle
(0x01b13400) (0x01b13401)
based on value of its x 5 x 45
attributes. y 15 y 80
●
State is modified by width 20 width 20
methods (ideally) height 15 height 25
06.10.2025 Java 1 35
Reference vs. instance
●
Another instance is created only by operation new.
●
Reference to the same instance is passed during assignment.
Rectangle rectangl1 = new Rectangle();
[Link]();
Rectangle (0x01010000)
Identifiers refers the same
instance.
//...
Rectangle rectangl2 = rectangl1;
Only reference is Rectangle (0x01010000)
assigned.
06.10.2025 Java 1 36
Variables
●
Again similar to C/C++ (instance, local, static, methods arguments)
except:
– There is no global variable – every declaration should be placed inside
class or their methods or other blocks
●
default value depends on data type and variable type (local,
instance, static) – local variables need explicit definition of initial
value
06.10.2025 Java 1 37
Accessing Uninitialized Variables
●
If variables aren’t initialized, Data Type Default Value
they take on a default value. boolean false
●
Not true for local int 0
variables!!!!! double 0.0
●
Java provides the following String null
default values: Any Object type null
06.10.2025 Java 1 38
Defining constants
●
variable with modifier final – its value cannot be changed
private final int year;
●
It is good practice to define variable as final when it is not changed in
the future.
●
Instance variable needs to be initialized in a constructor or by default
value during declaration.
private final int year = 2024;
06.10.2025 Java 1 39
Null Object reference
●
Variables of object type can have a null value.
●
A null object points to an empty location in memory
●
If an Object has another Object as a field (such as a String), its default value is
null.
●
What if a null object contains a field or method that needs to be accessed?
– This causes the program to crash!(It is possible to handle it!)
– The specific error is a NullPointerException.
public static void main(String[] args) {
String test = null;
[Link]([Link]());
}
06.10.2025 Java 1 40
Java Classes in Source Code
06.10.202 Java 1 41
5
Comparing Variables (values)
●
When you compare values by using boolean expressions, you need
to understand the nuances of certain data types.
●
Relational operators such as == are …
– Great for comparing primitives
– Terrible for comparing Strings (and other objects)
06.10.2025 Java 1 42
Comparing Primitives
●
The value z is set to be the sum of x + y.
●
When a boolean expression tests the equality between z and the
sum of x + y, the result is true.
int x = 3;
int y = 2;
int z = x + y;
boolean test = (z == x + y);
[Link](test); // true
06.10.2025 Java 1 43
Comparing Strings (true for objects)
●
The value z is set to be the concatenation of x + y.
●
When a boolean expression tests the equality between z and the
concatenation of x + y, the result is false.
String x = "Ora";
String y = "cle";
String z = x + y;
boolean test = (z == x + y);
[Link](test); // false
06.10.2025 Java 1 44
Why Are There Contradictory Results?
●
Primitives and objects are stored differently in memory.
– Strings are given special treatment.
– This is discussed later in the course.
●
As a result ...
– == compares the values of primitives.
– == compares the objects’ locations in memory.
●
It’s much more likely that you’ll need to compare the content of
Strings and not their locations in memory.
06.10.2025 Java 1 45
How Should You Compare Strings?
●
You should almost never compare Strings using ==.
●
Instead, compare Strings using the equals() method.
– This method is part of the String class (part of every class).
– It accepts one String argument, checks whether the contents of Strings are equal,
and then returns a boolean.
– There is also a similar method, equalsIgnoreCase()
String x = "Ora";
String y = "cle";
String z = x + y;
boolean test = [Link](x + y);
[Link](test); // true
06.10.2025 Java 1 46
Java Classes in Source Code
06.10.202 Java 1 47
5
Definition of class
●
Every class have to be within own source file named “<class-
name>.java” - following class Person is in file [Link].
●
Name of class should follow conventions -
●
Name should be noun, in mixed case with the first letter of each
internal word capitalized.
●
All class definitions are inside class block ({})
●
Visibility modifiers(public, private, protected) should be placed
before every defined element.
06.10.2025 Java 1 48
Structure of a Class
public class Person {
private LocalDate birthDay;
private int actualIq;
public Person() {
this([Link]());
}
public Person(LocalDate aBirthDay) {
this(aBirthDay, 110);
}
public Person(LocalDate aBirthDay, int actualIq) {
birthDay = aBirthDay;
[Link] = actualIq;
}
public void run(int maxSpeed) {
// process of running
}
private int getActualAge() {
int result;
result = [Link](birthDay, [Link]()).getYears();
return result;
}
}
06.10.2025 Java 1 49
Class and Constructors
●
Class constructor is always called when object is created (using
keyword new)
●
If constructor is not deffined, Java automatically create default empty
constructor without parameters.
06.10.2025 Java 1 50
Complicated construction of objects
Default value is often passed to some parameters:
●
red rectangle is most common;
new Rectangle(0, 0, 50, 20, [Link]);
new Rectangle(10, 20, 10, 25, [Link]);
new Rectangle(10, 30, 5, 2, [Link]);
●
but sometimes we need a rectangle of different color.
new Rectangle(15, -5, 30, 5, [Link]);
06.10.2025 Java 1 51
Overloading Constructors
●
You can write more than one constructor in a class.
– This is known as overloading a constructor.
– A class may have an unlimited number of constructors.
●
Each overloaded constructor is named the same.
●
But they differ in any of the following ways:
– Number of parameters.
– Types of parameters.
– Ordering of parameters.
06.10.2025 Java 1 52
Overloaded constructor example
public class Rectangle {
int x;
int y;
int width;
int height;
Color color;
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
[Link] = width;
[Link] = height;
}
public Rectangle(int x, int y, int width, int height, Color color) {
super();
this.x = x;
this.y = y;
[Link] = width;
[Link] = height;
[Link] = color;
}
}
06.10.2025 Java 1 53
Calling Overloaded Constructors
●
An object may be instantiated by calling any of its class constructors.
●
You supply the arguments, and Java finds the most appropriate
constructor.
●
Overloading is used substitutes missing construction default values
of parameters.
new Rectangle(10, 30, 5, 2);
new Rectangle(15, -5, 30, 5, [Link]);
06.10.2025 Java 1 54
Recognizing Redundancy in Constructors
●
Very similar code is repeated in these constructors.
●
It’s possible to minimize this redundancy.
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
[Link] = width;
[Link] = height;
[Link] = [Link];
}
public Rectangle(int x, int y, int width, int height, Color color) {
this.x = x;
this.y = y;
[Link] = width;
[Link] = height;
[Link] = color;
}
06.10.2025 Java 1 55
Constructors Can Call Other Constructors
●
By using the this keyword, one constructor may call another.
public Rectangle(int x, int y, int width, int height) {
this(x, y, width, height, [Link]);
}
public Rectangle(int x, int y, int width, int height, Color color) {
this.x = x;
this.y = y;
[Link] = width;
[Link] = height;
[Link] = color;
}
06.10.2025 Java 1 56
Overloading Methods
●
Any method can be overloaded, including ...
– Constructors
– Methods that model object behaviors
– Methods that perform calculations
●
All versions of an overloaded method are named the same.
●
But differ in any of the following ways(in a signature of the method):
– Number of parameters
– Types of parameters
– Ordering of parameters
●
Which version of overloaded methods is chosen during compilation –
important when we use object types and inheritance.
06.10.2025 Java 1 57
Methods Can Call Other Methods in the Same Class
●
In this example, one method returns a value to the other.
public class Calculator {
public double calcY(double m, double x) {
return calcY(m, x, 0);
}
public double calcY(double m, double x, double b) {
return m * x + b;
}
}
06.10.2025 Java 1 58
Not the Method Signature
●
The method signature does not include ...
– Name of parameters
– Method return type
●
Changing either of these isn’t enough to overload a method.
public double calcY(double m, double x)
public void calcY(double m, double z)
These aren’t part of method signature
06.10.2025 Java 1 59
Not Matching Return Types
●
Can you tell which version of sum() should be called if the return
types differ?
– No.
– And neither can Java.
public double sum(double num1, double num2) {
return num1 + num2;
}
public int sum(double num1, double num2) {
return num1 + num2;
}
06.10.2025 Java 1 60
Enumeration
public enum Action { public enum Direction {
NORTH(0, 1), SOUTH(0, -1), EAST(1, 0),
RUN, STOP, KILL; WEST(-1, 0);
}
private int x;
private int y;
●
Special object type
private Direction(int x, int y) {
●
Ensures uniqueness of values this.x = x;
– allow use comparison this.y = y;
operators == and != }
●
Allow define public String printVector() {
constructors(private), methods return [Link]("[%d, %d]", x, y);
}
and variables (constant) }
06.10.2025 Java 1 61
Java control structures
06.10.202 Java 1 62
5
Legacy from C/C++
●
Very similar ●
Conditional expression has to
– Block of code be boolean type (implicit
– If, If/else conversion from int is not
allowed)
– Ternary operator
– Switch
●
Types used in switch -
primitive: byte, char, short, int;
– Loops (for, while, do-while)
object: String, enumeration
– Break, continue (enum)
●
●
for exists in a form of a for-
each construction.
06.10.2025 Java 1 63
Loop control Improvements
loop: while (true) {
for (int i = 0; i < 100; i++) {
switch (c = [Link]()) {
case -1:
case '\n': Loop flow control with label
break loop; // jumps out while
// ...
}
}
test: for (int i = 0; i < 100; i++) {
while (true) {
if (i > 10)
continue test; // jumps to next iteration of for
}
// ...
}
}
06.10.2025 Java 1 64
Additional switch construction in Java 12
●
Prevents from error String text = switch (x) {
case 1 -> "Foo";
●
simpler for an one command
default -> "Bar";
alternatives
};
switch (x) {
case 1 -> [Link]("Foo");
default -> [Link]("Bar");
}
06.10.2025 Java 1 65
Arrays
●
Instance of special class – beside declaration needs creation with
new
●
operator [], constant length, method clone
●
Many useful methods for manipulation in [Link]
●
more available ways for declaration and instantiation:
int[] params = new int[3];
int params2[] = new int[3];
String[] values = new String[] { "one", "two" };
String[] values2 = { "one", "two" };
06.10.2025 Java 1 66
Multidimensional arrays and copy
int[][] twoDimensionalArray = new int[3][4];
int[][] anotherTwoDimensionalArray = new int[3][];
for (int i = 0; i < [Link]; i++) {
anotherTwoDimensionalArray[i] = new int[i * 10];
}
int[] arrayOfInts = new int[10];
int[] newArrayOfInts = [Link](arrayOfInts, [Link]);
06.10.2025 Java 1 67
for-each Loop vs. for Loop
for-each loop
for (String name : names) {
[Link](name);
}
for loop
for (int idx = 0; idx < [Link]; idx++) {
[Link](names[idx]);
}
●
The output of both loops is the same.
06.10.2025 Java 1 68
What is an ArrayIndexOutOfBoundsException?
● As you already know, an array has a fixed size.
●
The index must be in a range interval [0, n-1], where n is the size of
the array.
●
If an index is either negative or greater than or equal to the size of
the array, then the array index is out of bounds.
●
If an array index is out of bounds, the JVM throws an
ArrayIndexOutOfBoundsException.
●
This is called automatic bounds checking.
06.10.2025 Java 1 69
What Happens When This Exception Occurs?
●
The ArrayIndexOutOfBoundsException is thrown only at run time.
●
The Java compiler doesn't check for this exception when a program
is being compiled.
●
The program is terminated if this exception isn't handled.
06.10.2025 Java 1 70
How Do You Identify the ArrayIndexOutOfBoundsException?
int primes[] = { 2, 3, 5, 7, 11, 13, 17 };
[Link]("Array length: " + [Link]);
primes[10] = 20; //
[Link]("The first few prime numbers are:");
for (int i : primes) {
[Link](i);
} The index of the array is 0-6,
Output: and it's trying to access an
Array length: 7
element at index 10.
Exception in thread "main"
[Link]: 10
at arraysdemo. Arrays [Link] (Arrays [Link])
Java Result: 1
06.10.2025 Java 1 71
Method with a variation number of arguments
void methodWithVariableNumberOfParameters(int... params) {
[Link]("Number of parameters: " + [Link]);
int firstParam = params[0];
for (int param : params) {
[Link]("param = " + param);
}
}
// somewhere in code
methodWithVariableNumberOfParameters(12, 12, 2, 3);
06.10.2025 Java 1 72
Method with a variation number of arguments
●
an alternative declaration of a method parameter of array type
●
Declared with “…”
●
construction of array is not necessary in the case of a method
calling
●
Method is called with a variation number of parameters separated by
“,”
●
Parameters are accessed in the method as they were in an ordinary
array
06.10.2025 Java 1 73
2nd lesson
●
Libraries and packages
●
String, Math, Random, System
●
Memory management
●
Interfaces
●
Inheritance
●
Class Object
●
Abstract classes
●
Virtual Methods
●
JavaFX
●
06.10.2025 Java 1 74
Libraries and Packages
06.10.202 Java 1 75
5
Why Should You Reinvent the Wheel?
● Frequently, you may rewrite the same Java code for different
programs.
●
As an alternative to rewriting the same code, you can use the Java-
provided library, which organizes frequently used code.
●
This library is called as Java class library.
●
The Java class library documentation is available here:
– [Link]
06.10.2025 Java 1 76
Packages in the Java Class Library
●
The classes of the Java class library are organized into packages.
●
A package contains a group of related classes.
●
With a package, it becomes easier to locate the related classes.
06.10.2025 Java 1 77
Packages in the Java Class Library
Package Purpose
[Link] Provides classes that are fundamental to the design of the Java language
[Link] Provides classes to build GUI components
[Link] Provides classes for networking applications
[Link] Provides classes for dates, times, instants, and durations
06.10.2025 Java 1 78
How Are the Packages Organized?
●
The vast collection of classes java
are organized Into a tree-like
hierarchy, which allows
packages to be divided into [Link]
subpackages, like this:
[Link]
[Link]
[Link]
06.10.2025 Java 1 79
Using a Class from a Package
●
To use a class from a package in your program, you need to specify
its fully qualified name.
●
For example, to use the Scanner class to read a keyboard input the
fully qualified name for the Scanner class, which is defined in the
[Link] package is
[Link]
Package Class Name
06.10.2025 Java 1 80
Using the Full Qualified Class Name
public static void main(String[] args) {
int num;
[Link] keyboard = new [Link]([Link]);
[Link]("Enter a number");
num = [Link]();
[Link]("The entered number is " + num);
}
●
As you can see, using the fully qualified name creates very long
names for classes.
●
Long names reduce the readability of the code and also make
coding difficult.
06.10.2025 Java 1 81
Using the import Statement
●
You can avoid the fully qualified class name by using the import statement.
●
You place the import statement aboce your class definition. It looks like
this:
import [Link];
●
Example:
import [Link];
public class Numbers {
public static void main(String[] args) {
int num;
Scanner keyboard = new Scanner([Link]);
06.10.2025 Java 1 82
Accessing All classes from the [Link] Package
●
As you access more classes from the [Link] package in your
program, the number of import statements also increases.
●
To avoid this, you can import all classes from the [Link] package
by using the * wildcard character in the import statement, like this:
import [Link].*;
//import all class names
//from package [Link]
06.10.2025 Java 1 83
Identify Packages That Are Automatically Imported
●
So far, you have used [Link]() to print text to the
console.
public class DisplayOutput {
public static void main(String[] args) {
[Link]("Hello, how are you today?");
}
}
●
If you look at the Java library, you'll see that the System class is
organized in the [Link] package.
●
By default, the [Link] package is automatically imported into all
Java programs
06.10.2025 Java 1 84
Static import
●
It enables import one or more static elements of class.
//imports only static method assertTrue
import static [Link];
//imports all static methods
import static [Link].*;
//imported method is accessible without class specification
assertTrue(true);
06.10.2025 Java 1 85
Visibility modifiers
They are used with:
● public class MyClass {
private int a1;
– variables – both instance and
class String a2;
– methods public double a3;
– ...and also classes! public void method1() {
}
access public protected <none> private
The same void method2() {
YES YES YES YES
class }
The same
YES YES YES NO
package private void method3() {
}
successors YES YES NO NO
}
anywhere YES NO NO NO
06.10.2025 Java 1 86
Package accessible class
●
Package accessible class:
– could be in file that is named differently then class;
– could be in a file with another classes;
class IndexObject { Defined in source file:
int id; [Link]
Object value;
}
public class Database {
06.10.2025 Java 1 87
Libraries and JARs
●
Compiled classes could be CLASSPATH=.;d:\mylibs\[Link];d:\java
packed into one jar archive(zip java [Link]
format) and reused. ●
or
●
Also zip archive could be used. java –cp .;d:\myapp\[Link];d:\java
[Link]
●
JVM looks up classes relative
to the directories specified by .\user\bank\[Link]
the CLASSPATH environment
●
or
variable or by parameter – d:\mylibs\bank\[Link]
classpath (-cp) passed as
●
must exist, or the class is zipped in
[Link] including directory
argument for JVM ([Link]). specification!
06.10.2025 Java 1 88
Example Classes from Java Class Library
●
[Link] – known type, methods (length, isEmpty, substring,
indexOf, lastIndexOf, charAt, toLowerCase, toUpperCase)
●
[Link] – static variables (in, out, err), methods(exit, load,
currentTimeMillis, …)
●
[Link] – static methods (e.g. abs, sin, max) and variables
(PI)
●
[Link]
06.10.2025 Java 1 89
[Link] – another operations, basic I/O
●
Concatenation: ●
Output
– [Link](), [Link]()
– Operator ‘+’ … <String value> + – [Link](String format, Object …
<Any value including primitive args)
types>
–
●
Input
Method ‘concat’ – requires string – new Scanner([Link]) – nextLine,
value as parameter haseNextInt/nextInt …
●
Formatting
– [Link](String format, Object
●
String formatting similar as in
… args) C++
– [Link](CharSequence delimiter, [Link]("%f, %1$
CharSequence … args) +020.10f", 10.f,[Link]);
06.10.2025 Java 1 90
Memory management
06.10.202 Java 1 91
5
Object lifecycle
●
Objects are explicitly created with keyword new or some factory
method(internally using new). Enumeration values are exception.
●
When an object is no longer being used, it could release its memory
space.
●
Java virtual machine knows that it is not used whether no reference
to it exists.
06.10.2025 Java 1 92
Garbage collector – our friend
●
The collection and freeing of memory is the responsibility of a thread
of code called automatic garbage collector (GC).
●
GC starts:
●
low memory
●
explicit start – [Link]()
●
The garbage collector keeps track of all memory allocated with the
new key keyword and also tracks who has access to that memory.
When the access count reaches zero, the memory can be collected
and freed.
●
06.10.2025 Java 1 93
Strings Are Special Objects
●
Printing a String reference prints the actual String instead of the
object's memory address.
●
Strings can be instantiated with the new keyword.
– But you shouldn't do this.
String s1 = new String("Test");
●
Strings should be instantiated without new.
– This is more memory-efficient.
– We'll explore why in the next few slides.
String s2 = "Test";
06.10.2025 Java 1 94
Instantiating Strings with the new Keyword
● Using the new keyword creates String s1 = new String("Test");
String s2 = new String("Test");
two different references to two
different objects.
06.10.2025 Java 1 95
Instantiating Strings Without the new Keyword
String sl = "Test";
● Java automatically
String s2 = "Test";
recognizes identical
Strings and saves
memory by storing the
object only once.
●
This creates two
different references to
one object.
06.10.2025 Java 1 96
String References
●
Altering a String String s1 = "Test";
using one reference String s2 = "Test";
won't affect other s1 = "Different";
references.
●
Java allocates new
memory for a different
String.
06.10.2025 Java 1 97
Immutability of String object
●
String object is immutable – value cannot be changed
●
Each “modification” of String create new object with new value
String s3 = s1+s2;
String s4 = [Link]('T', 'B');
String s5 = [Link]();
String[] s6 = "a b c".split(" ");
06.10.2025 Java 1 98
Interfaces
06.10.202 Java 1 99
5
Simplify working with visible objects
public class World {
private final Object[] subjects = new Object[] {/*...*/};
public void draw(Graphics gc) {
// foreach call draw
}
public void simulate(double deltaT) {
// foreach call simulate
}
}
06.10.2025 Java 1 100
Need for new data type
●
Declares only methods without their implementation.
●
Object that implements interface should implement all declared
method.
●
Our solution works uniformly with objects through the specified
interface.
06.10.2025 Java 1 101
Interface
●
An interface is a Java construct that helps define the roles that an
object can assume – it allows treat with objects of different classes
uniformly
●
It is implemented by a class or extended by another interface.
●
An interface looks like a class with abstract methods (no
implementation), but we cannot create an instance of it.
●
Interfaces often define collections of related methods without
implementations.
●
All public methods in a Java interface are abstract (or default using
another methods in the interface).
06.10.2025 Java 1 102
Declaring Interface
●
To declare a class as an interface you must replace the keyword
class with the keyword interface.
●
This will declare your interface and force all methods to be abstract
and make the default access modifier public.
public interface DrawableSimulable {
void draw(Graphics gc);
void simulate(double deltaT);
}
06.10.2025 Java 1 103
Interface using in the new solution
public class World {
private final DrawableSimulable[] subjects =
new DrawableSimulable[] { /* ... */ };
public void draw(Graphics gc) {
for (DrawableSimulable i : subjects) {
[Link](gc);
}
}
public void simulate(double deltaT) {
for (DrawableSimulable i : subjects) {
[Link](deltaT);
}
}
}
06.10.2025 Java 1 104
Why Use Interface
●
When implementing a class from an interface we force it to
implement all of the abstract methods.
●
The interface forces separation of what a class can do, to how it
actually does it.
●
So a programmer can change how something is done at any point,
without changing the function of the class.
●
This facilitates the idea of polymorphism as the methods described
in the interface will be implemented by all classes that implement the
interface.
06.10.2025 Java 1 105
Interface properties
●
An interface: ●
A class
– Can declare public constants. – can implement more then one
– Define methods without interface
implementation, default method, ●
An interface method
private methods or static method. –
–
Each method is public even when
Can only refer to its constants and you forget to declare it as public –
defined methods or other accessible private methods are exception.
methods (static or methods of –
objects passed as parameter). Is implicitly abstract but you can
–
also use the abstract keyword.
Can be used with the instanceof –
operator. Each variable is public final static –
even without modifier.
06.10.2025 Java 1 106
Default (Java 8) and private (Java 9) methods
●
These methods can not deal public interface Movable {
with inner structure void setPosition(int x, int y);
int getX();
●
Help remove redundancy in int getY();
code and extend existing
interface default void moveRight() {
move(10, 0);
}
private void move(int dx, int dy) {
setPosition(getX() + dx, getY() + dy);
}
}
06.10.2025 Java 1 107
Interface Implementation
public class Rectangle implements Paintable {
// ...
@Override
public void paint(MyGraphics d) {
// ... Class declares
} implementation of
specified interface.
It has to implement every
method of specified interface.
06.10.2025 Java 1 108
Multiple Interface implementation
●
Every class could implement more then one interface.
public class Rectangle implements Paintable, Clear {
// ...
●
When are implemented two or more interfaces with same default methods then these
methods should be overridden. It could call one of the existing implementations.
public class MyClass implements Movable, Pickable {
@Override
public void moveRight() {
[Link]();
}
06.10.2025 Java 1 109
Design pattern Template method
●
Common logic is placed externally of class.
●
Class is accessed through defined interface.
06.10.2025 Java 1 110
Design pattern Template method in source code
public class Mover {
private static final long SLEEP_TIME_IN_MS = 500; Common behavior is
private static final double SPEED = 10; in a separate class
public void move(IMovable object, int toRight, int toDown) {
double distance = [Link](toRight * toRight + toDown * toDown);
int STEPS = (int) (distance / SPEED);
double dx = (toRight + 0.4) / STEPS;
double dy = (toDown + 0.4) / STEPS; The algorithm – behavior will be
int xPos = [Link]();
int yPos = [Link](); applicable on any object that
double x = xPos + 0.4; implements a specific interface
double y = yPos + 0.4;
for (int i = STEPS; i > 0; i--) {
x = x + dx;
y = y + dy; public interface IMovable {
[Link]((int) x, (int) y); int getX();
[Link](SLEEP_TIME_IN_MS);
}
} int getY();
}
void setPosition(int x, int y);
06.10.2025 Java 1 } 111
Interface extension
●
If class implement the interface IMovable than it must also
implement interface IPaintable.
public interface IMovable extends IPaintable {
06.10.2025 Java 1 112
Interface extends multiple interfaces
●
Interface can extend from multiple interfaces.
●
When are extended two or more interfaces with same default
methods then these methods should be overridden as default - it
could call one of the existing implementations (similar to
implementation) – or leave them as abstract.
06.10.2025 Java 1 113
Class extension - inheritance
●
Rectangle is specialization of
MovableShape.
●
MovableShape is generalization of
Rectangle.
●
Rectangle is subclass (successor)
of MovableShape.
●
MovableShape is superclass
(predecesor) of Rectangle.
06.10.2025 Java 1 114
Inheritance in Java
●
Class could inherit only from one another class in Java.
●
If a superclass is not specified than class inherits from class Object.
public class Rectangle extends MovableShape {
06.10.2025 Java 1 115
Inheritance of constructors
class ParentClassType {
private int parentValue;
●
Constructors are not inherited
public ParentClassType() { in successors.
parentValue = 10;
}
new ClassType(10);
public ParentClassType(int value) {
parentValue = value;
[Link](
"Parent constructor called");
}
}
●
Only default non-parametric
constructor is available in this
public class ClassType
extends ParentClassType {
case.
} new ClassType();
06.10.2025 Java 1 116
Implicit calling of predecessor constructor
class ParentClassType { public class ClassType extends ParentClassType {
private int parentValue; private int value;
public ParentClassType() { public ClassType() {
[Link]("Parent constructor called "); [Link]("Child constructor called ");
} value = 0;
public ParentClassType(
}
int value) {
[Link]("Parent constructor called " + "with
public ClassType(int value) {
value " + value); [Link]("Child constructor called ");
parentValue = value; [Link] = value;
} }
} }
●
Both constructors ●
Non-parametric constructor of
new ClassType(); predecessor (ParentClassType)
new ClassType(10);
●
Product output:
is implicitly called at the
Parent constructor called beginning of object construction
Child constructor called
06.10.2025 Java 1 117
Explicit calling of predecessor constructors
class ParentClassType { public class ClassType
private int parentValue; extends ParentClassType {
public ParentClassType( private int value;
int value) {
parentValue = value; public ClassType() {
} super(7);
} value = 10;
}
●
Explicit call of a specific parent public ClassType(
constructor is by keyword int value) {
super(7);
super in child constructor. It [Link] = value;
has to be first statement in }
}
constructor of child.
06.10.2025 Java 1 118
Instance building
class ParentClassType { public class ClassType
private int parentValue; extends ParentClassType {
private int value;
public ParentClassType() {
} public ClassType() {
this(10);
}
public ParentClassType(int value) {
parentValue = value; public ClassType(int value) {
} this(value, 7);
} }
public ClassType(int value,
●
If this(…) or super() are used, int parentValue) {
super(parentValue);
[Link] = value;
then it should be first statement }
in constructor. Otherwise public ClassType(String anotherValue) {
[Link](
nonparametric constructor of "Child constructor called with value "
+ anotherValue);
predecessor is called. }
}
06.10.2025 Java 1 119
Disadvantage of inheritance
●
It breaks encapsulation principle
●
it is necessary to know details of implementation in super-class.
●
Composition is preferred.
06.10.2025 Java 1 120
Method overriding
class ParentClassType {
●
Method redefined in successor public void methodA() {
// some implementation
are marked with annotation }
// of methodA
@Override. public void methodB() {
}
}
●
Overriding method should have public class ClassType
same signature and extends ParentClassType {
compatible return type: @Override
public void methodA() {
// statements before
●
same in case of a primitive type [Link]();
// statements after
}
●
same or a subtype in case of public void methodC() {
}
an object type }
06.10.2025 Java 1 121
Disadvantage of inheritance
●
It breaks encapsulation principle
●
it is necessary to know details of implementation in super-class.
●
Composition is preferred.
06.10.2025 Java 1 122
Casting object variables, operator instanceof
●
Variable of object type is implicitly boolean b =
casted to a supertype – predecessor val instanceof String;
or type of interface implemented by
the given type.
●
Variable of a object type could be if (val instanceof String) {
explicitly casted to a its subtype: String s = (String) val;
– An interface implemented by object [Link]();
– A class that is a super class or a class
of the object. }
●
Casting to a unfit type fails during
runtime – ClassCastException is if (val instanceof String s) {
thrown. [Link]();
●
Binary operator instanceof is used for }
testing whether object is given type
06.10.2025 Java 1 123
Supertype Class Object
●
Root node in a hierarchy of all Java classes – supertype.
●
Contains fundamental methods provided by all object:
– toString
– equals
– hashCode
– getClass
– notify, notifyAll, wait
– ...
06.10.2025 Java 1 124
Overriding of equals method
public class Fraction {
final private int numerator;
final private int denominator;
public Fraction(int numerator, int denominator) {
[Link] = numerator;
[Link] = denominator;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Fraction) {
Fraction other = (Fraction) obj;
if (denominator == [Link]
&& numerator == [Link])
return true;
}
return false;
}
}
06.10.2025 Java 1 125
Overriding of toString method
public class Fraction {
final private int numerator;
final private int denominator;
public Fraction(int numerator, int denominator) {
[Link] = numerator;
[Link] = denominator;
}
@Override
public String toString() {
return numerator + "/" + denominator;
}
}
06.10.2025 Java 1 126
Complete meaning of a final modifier
●
used with:
– variable – its value cannot be changed
private final int year;
– method – cannot be overridden
public final void someMethod() {/*implemntation*/}
●
class – cannot be subclassed (be parent to another class)
public final class MyDate {
06.10.2025 Java 1 127
Abstract Classes
●
An abstract method has no body; it has a signature definition followed by a
semicolon, e.g.
public abstract void method();
●
Any class with an abstract method must be abstract – it needs keyword
abstract before class.
●
An abstract class cannot be instantiated.
●
An abstract class can have a constructor that will be called when a
subclass is instantiated.
●
A subclass of an abstract class can be instantiated if it implements each of
the abstract methods.
●
This concept is defined a common predecessor for classes that share inner
structure or implementation.
06.10.2025 Java 1 128
Virtual method
●
All methods(functions) except final, private and static are virtual.
●
Virtual machine (Java Hotspot) could make virtual method non-
virtual or even inline during optimization and conversion into a native
code but programmer do not need take care about.
06.10.2025 Java 1 129
Class Lifecycle - Full
public class ClazzLifeCycle { private final int field1 = statMethod1();
private final int field2 = method1();
static { private int field3 = method1();
[Link]("Static Initializer 1"); private final int field4 = 4;
statField4 = 5; private final int field5;
} private final int field6;
private static final int statField1 = statMethod1(); {
private static int statField2 = statMethod1(); [Link]("instance initializer block 2");
private static int statField3 = 5; }
private static final int statField4;
public ClazzLifeCycle() {
static { field6 = 6;
[Link]("Static Initializer 2"); [Link]("Constructor");
} }
private static int statMethod1() { private int method1() {
[Link]("Static method 1"); [Link]("Method 1");
return 1; return 2;
} }
public static void main(String[] args) {
{ new ClazzLifeCycle();
[Link]("instance initializer block 1"); }
field5 = 5;
} }
06.10.2025 Java 1 130
JavaFX – Introduction
●
software platform for UI of desktop applications
●
initial release – 4.12.2008
●
last stable – 13. 9. 2022
●
MVC:
●
View defined in XML (named FXML) or programming language
●
Model, Controller – defined in programming language (compiled to Java
byte code)
●
declared as replacement of the Swing library
●
could be embedded into AWT/Swing applications
●
support moved to Gluon company
●
could be used for cross-platform mobile development
06.10.2025 Java 1 131
JavaFX – Creating JavaFX program
public class JavaFXTest StackPane root = new StackPane();
extends Application { [Link]().add(btn);
Scene scene = new Scene(
@Override root, 300, 250);
public void start(Stage primaryStage) { [Link](
Button btn = new Button(); "Hello World!");
[Link]("Say 'Hello World'"); [Link](scene);
[Link]( [Link]();
new EventHandler<ActionEvent>() { }
@Override
public void handle(
ActionEvent event) { public static void main(
[Link]( String[] args) {
"Hello World!"); launch(args);
} }
}); }
06.10.2025 Java 1 132
JavaFX – Two Methods: start() and main()
start() is the entry point for all JavaFX applications.
– Think of it as the main method for JavaFX.
public void start (Stage primaryStage) {
//...
}
main() is still required in your programs.
– It launches the JavaFX application.
public static void main(String[] args) {
launch(args);
}
06.10.2025 Java 1 133
JavaFX – Buttons Are Objects
●
Buttons are like any other object.
– They can be instantiated.
– They contain fields.
– They contain methods.
public void start(Stage primaryStage) {
Button btn = new Button();
[Link]("Say 'Hello World'");
//...
}
●
From this code, we can tell...
– Buttons contain a text field.
– Buttons contain a method for changing the text field.
06.10.2025 Java 1 134
JavaFX – Buttons Are Nodes
● Some of these fields and methods are designed to store and
manipulate visual properties:
[Link]();
[Link](5);
[Link](11.5); //set x position
[Link](20); //set y position
[Link](); //is it pressed?
●
Objects like this are called JavaFX Nodes.
06.10.2025 Java 1 135
JavaFX – Nodes
●
There are many types of JavaFX Nodes
●
Visual objects you’ll create will most likely …
– Be a Node, or
– Include a Node as a field
06.10.2025 Java 1 136
JavaFX – Node Interaction
●
The following helps handle Button interaction:
public void start(Stage primaryStage) {
// ...
[Link](new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
[Link]("Hello world!!");
}
});
// ...
}
●
This is called an "anonymous inner class."
– Doesn't the syntax look messy?
– Java SE 8 Lambda expressions are an elegant alternative.
– We'll discuss Lambda expressions later in this section.
06.10.2025 Java 1 137
JavaFX – Creating Nodes
●
Nodes are instantiated like any other Java object:
public void start(Stage primaryStage) {
Button btn1 = new Button();
Button btn2 = new Button();
[Link]("Say 'Hello World'");
[Link]("222");
}
●
After you instantiate a Node:
– It exists and memory is allocated to store the object.
– Its fields can be manipulated, and methods can be called.
– But it might not be displayed ...
06.10.2025 Java 1 138
JavaFX – Root Node - Displaying Nodes
●
There are a few steps to displaying a node.
public void start(Stage primaryStage) {
Button btn1 = new Button();
Button btn2 = new Button();
[Link]("Say 'Hello World'");
[Link]("222");
StackPane root = new StackPane();
[Link]().add(btn1);
[Link]().add(btn2);
}
●
First, add each Node to the Root Node.
– It's usually named root.
– It's very much like an ArrayList of all Nodes.
06.10.2025 Java 1 139
JavaFX – Adding Nodes to the Root Node
●
You could add each Node separately:
[Link]().add(btn1);
[Link]().add(btn2);
[Link]().add(btn3);
●
Or you could add many Nodes at once:
[Link]().addAll(btn1, btn2, btn3);
●
But don't add the same Node more than once.
– This causes a compiler error:
[Link]().add(btn1);
[Link]().add(btn1);
06.10.2025 Java 1 140
JavaFX – StackPane Root Node
●
The Root Node in this example is a StackPane.
StackPane root = new StackPane();
[Link]().addAll(btn1, btn2);
●
- The StackPane stacks Nodes on top of each other.
●
- But small buttons could become buried and unreachable.
06.10.2025 Java 1 141
JavaFX – Panes as Root Nodes
●
Each Pane determines the layout of Nodes.
06.10.2025 Java 1 142
JavaFX – Programming Different Panes as Root Nodes
●
It's easy to design the root node as a different pane.
●
Just specify a different reference type and object type.
StackPane root = new StackPane();
TilePane root = new TilePane();
VBox root = new VBox();
[Link]().addAll(btn1, btn2);
06.10.2025 Java 1 143
JavaFX – Group Root Node
●
A Group allows you to place Nodes anywhere.
Group root = new Group();
[Link]().addAll(btn1, btn2);
[Link](100);
●
A pane may restrict where Nodes are placed.
– You couldn't move them even if you wanted to.
– You couldn't click and drag a node that's locked in a pane.
StackPane root = new StackPane();
[Link]().addAll(btn1, btn2);
[Link](100); // Has no effect
06.10.2025 Java 1 144
JavaFX – A Group Can Contain a Pane
●
Panes are also Nodes.
– Any node can be added to the Root Node.
●
A Pane may be a good option for storing buttons, text input dialog
boxes, and other GUI elements.
– You can't quite move individual Nodes in a Pane.
– But you can move the entire Pane in a Group. Move the Pane like you
would any other Node.
06.10.2025 Java 1 145
JavaFX – The JavaFX Scene Graph
How you decide to add nodes can be drawn as a Scene Graph.
●
The Root Node contains an HBox.
●
The HBox acts as a container for buttons.
06.10.2025 Java 1 146
JavaFX – The Scene Graph
●
The HBox keeps the GUI organized and conveniently located.
●
The rest of the window could be used for other Nodes.
06.10.2025 Java 1 147
JavaFX – The Scene and Stage
If we look at the rest of the default JavaFX program, we notice two more
things:
●
A Scene (which contains the Root Node)
●
A Stage (which contains the Scene)
public void start(Stage primaryStage) {
// ...
Scene scene = new Scene(root, 300, 250);
[Link]("Hello World!");
[Link](scene);
[Link]();
}
06.10.2025 Java 1 148
JavaFX – What Is the Scene?
There are a few notable properties that describe a Scene:
●
Scene Graph
– The Scene is the container for all content in the JavaFX Scene Graph.
●
Size
– The width and height of the Scene can be set.
●
Background
– The background can be set as a Color or Background Image.
●
Cursor Information
– The Scene can detect mouse events and handles cursor properties.
Scene scene = new Scene (root, 300, 250, [Link]);
06.10.2025 Java 1 149
JavaFX – What Is the Stage?
●
Think of the Stage as the application window.
●
Here are two notable Stage properties:
●
Title
– The title of the Stage can be set.
●
Scene
– The Stage contains a Scene.
[Link]("Hello World!");
[Link](scene);
[Link]();
06.10.2025 Java 1 150
JavaFX – Hierarchy Animation
●
A Stage is the top-level
container.
●
A Stage contains a Scene.
●
A Scene contains a Root Node.
●
The Root Node contains other
Nodes.
06.10.2025 Java 1 151
JavaFX – Many Scenes, One Stage
●
It's possible to swap any scene into a single Stage.
06.10.2025 Java 1 152
JavaFX - Many Scenes, One Stage
●
It's possible to swap any scene into a single Stage.
06.10.2025 Java 1 153
JavaFX – Many Scenes, Many Stages
●
Many Scenes, Many
Stages
●
It's also possible to
create many Stages.
06.10.2025 Java 1 154
JavaFX – Color
What Can I Do with Colors in JavaFX?
●
Color shapes
●
Create gradients
●
Colorize images
06.10.2025 Java 1 155
JavaFX – Contains a Color Class
●
Colors can be stored as variables:
Color color = [Link];
●
Colors can be passed in methods:
Scene Scene = new Scene (root, 300, 250, Color. BLACK);
– This example makes the scene's background black.
●
But before using any Color …
– You'll first need to make the following import:
import [Link];
●
- Ignore IDEs' other Color import suggestions.
JavaFX – Referencing a Color
●
There are many colors in
JavaFX.
●
Typing Color. in IDE reveals
the entire list of possible colors.
JavaFX – Customizing a Color
●
If you're unhappy with the colors that JavaFX provides, there are
ways to customize your own color.
●
The Color class contains methods to do this:
– Customize a color by mixing red, green, and blue components.
– Opacity can also be controlled.
JavaFX – The Range of Color Components
JavaFX – Color Example
●
In this example, the resulting color contains ...
Color color = [Link](255, 255, 20);
– As much Red as possible
– As much Green as possible
– Only a little Blue
●
The resulting color is very close to yellow.
– But how do we know this?
– For the most part, finding the perfect color is "guess and check," but there
are guiding principles.
JavaFX –
●
● Rules of Additive Color Mixing
● RED
● GREEN
● BLUE
● Examples:
● Code
● Color
● [Link](255,
● 0,
● );
● red
● Pure red
● [Link](0,
● 255,
● );
● [Link] (0,
● 0,
● 255);
● green blue
● Pure green
● Pure blue
● [Link](255,
JavaFX – Shapes
●
This Is a Rectangle
●
This is how to instantiate a JavaFX Rectangle:
Rectangle rect = new Rectangle ( 20, 20, 250, 100);
// x-pos, y-pos, width, height
●
You'll first need to make the following import:
import [Link];
JavaFX – Important Methods for Rectangles
●
We can get a sense of a Rectangle's properties from the constructor and
the following methods:
●
setX(double d)
●
setY(double d)
●
setWidth(double d)
●
setHeight(double d)
●
setFill(Paint paint)
●
setStroke(Paint paint)
●
setStrokeWidth(double d)
●
(There are many more Rectangle methods besides these seven.)
●
But what exactly will these methods do?
JavaFX – Shapes
Method Descriptions, Part 1
●
setFill(Paint paint)
– Sets the color of the Rectangle
●
setStroke(Paint paint)
– Sets the color of the Rectangle's outline
●
setStrokeWidth(double d)
– Sets the width of the Rectangle's outline
JavaFX – Shapes
Method Descriptions, Part 2
●
setX(double d)
●
setY(double d)
– Sets the x or y position of the Rectangle
●
setWidth(double d)
●
setHeight(double d)
– Sets the width or height of the Rectangle
JavaFX – Changing a Node's Position
●
We've seen a couple ways to change a node's position ... but which way is
preferable?
●
setX(double d)
●
setY(double d)
– These are preferable in most cases.
●
setLayoutX (double d)
●
setLayoutY (double d)
– Use these if your Node is locked in a Layout pane, such as a FlowPane.
– setX() definitely won't work in this case.
– Or if setX() is unavailable, which is the case with UI elements, such as Buttons.
JavaFX – Positioning a Node
● Most Nodes are positioned with
respect to their top-left corner.
– And not with respect to their
geographic center.
●
If you call setX (100) on a Node
...
– The x-position of the Node's top-
left corner is set to 100.
JavaFX – Coordinate Systems
Mathematical Coordinate JavaFX Coordinate System
System ●
The origin is located at the top-
●
The origin is located at the left corner.
bottom-left corner. ●
The y-axis is backward.
●
JavaFX – Positioning Example
●
This Rectangle is positioned at
(4,2) by calling:
– setX (4);
– setY (2);
JavaFX
• Introduction
• Creating JavaFX program
• Root Node
• Scene Graph, Scene, Stage
• Color
• Shapes
• Graphics
• Audio
• Mouse Events
JavaFX – Using Your Own Graphics
●
FX can provide UI elements, shapes, and text.
– But if you have a talent for art, you can use your own graphics in place of those that
JavaFX provides.
●
For example:
– The art for the level-select button wasn't created by JavaFX.
– But we used JavaFX to procedurally add level numbers, text, and the graphic of Duke.
JavaFX – Image and ImageView
●
An Image is an object that describes the location of a graphics file
(.png, .jpg, .gif, …).
Image image;
String imagePath = "Images/[Link]";
image = new Image(getClass().getResource(imagePath).toString());
image = new Image(getClass().getResourceAsStream(imagePath));
●
An ImageView is the actual Node.
– Calling its constructor requires an Image argument.
ImageView imageView = new ImageView(image);
– An ImageView also contains the same properties as any other node:
x-position, y-position, width, height ...
JavaFX – Why Have Both an Image and ImageView?
● One big advantage is animation.
– Images can be swapped in and out of the same ImageView.
●
The Fan in Java Puzzle Ball takes advantage of this.
– The fan cycles through 2 images when it's blowing.
●
Custom buttons also benefit.
– You could use different images for buttons depending on their state:
●
Is the mouse hovering over the button?
●
Is the user clicking the button?
JavaFX – ImageView Hints
●
How to create Images:
Image image1 = new Image(
getClass().getResource("Images/[Link]").toString());
Image image2 = new Image(
getClass().getResourceAsStream("Images/[Link]"));
●
How to create an ImageView:
ImageView imageView = new ImageView(image1);
●
How to swap an Image into an ImageView:
[Link](image2);
– imageView retains its properties, such as positioning.
●
Remember to import
– [Link];
– [Link];
JavaFX – File Locations
●
Make sure files are in the correct location.
Image image = new
Image(getClass().getResourceAsStream("Images/[Link]"));
●
Images/[Link] refers to a folder relative to class folder/package
(If using maven same folder but inside resources folder not src
folder )
JavaFX – Scaling a Node
● It's very easy to make a
rectangle wider:
●
But if you try the same thing
with an ImageView …
– It might look awful!
JavaFX – Scaling a Node the Right Way
● JavaFX is very good at scaling graphics.
– The quality of the image is less likely to deteriorate
●
You have the option to preserve the aspect ratio of an ImageView.
– An ImageView's width and height scale together.
– This avoids distortion.
[Link](true);
[Link](25);
JavaFX – Ordering Nodes
●
Sometimes, testers of Java Puzzle
Ball didn't realize that their goal
was to get the ball to Duke.
●
We thought adding a baseball
glove would help solve the
problem.
●
Duke and the glove are two
separate ImageViews.
– These needed to be ordered
properly so that the glove doesn't
display behind the hand.
JavaFX – Ordering Nodes the Right Way
●
●
• The order that Nodes are added to the Root Node determines the order
that they are displayed.
●
Nodes added early are buried under nodes added later.
[Link]().addAll(gloveImageView, dukeImageView);
●
To fix this you could...
– Change the order that Nodes are added to the Root Node.
– Bring an ImageView to the front or back.
// Either one of these will solve the problem
[Link]();
[Link]();
JavaFX
• Introduction
• Creating JavaFX program
• Root Node
• Scene Graph, Scene, Stage
• Color
• Shapes
• Graphics
• Audio
• Mouse Events
JavaFX – Image and Audio Similarities
● Creating a JavaFX Image object ...
Image image1 =
new Image(getClass().getResource("Images/[Link]").toString());
●
Is very similar to creating a JavaFX Audio object.
AudioClip audio =
new AudioClip(getClass().getResource("Audio/[Link]").toString());
●
It's common to store images and audio in their own
packages/folders.
JavaFX – Image and Audio Differences
●
An Audio object describes the location of an audio file
(.wav, .mp3 ...).
AudioClip audio =
new AudioClip(getClass().getResource("Audio/[Link]").toString());
●
And unlike an Image ...
●
There is no Audio equivalent of an ImageView.
●
Audio can be played by referencing the Audio object directly.
[Link]();
●
There are many other Audio methods you can call.
JavaFX
• Introduction
• Creating JavaFX program
• Root Node
• Scene Graph, Scene, Stage
• Color
• Shapes
• Graphics
• Audio
• Mouse Events
JavaFX – Mouse and Keyboard Events
●
Nodes can detect mouse and keyboard events.
– This is true about ImageViews, too!
– You aren't limited to buttons and other GUI components.
●
Helpful methods to make this happen include:
– setOnMouseClicked()
– setOnMouseDragged()
– setOnMouseEntered()
– setOnMouseExited()
– setOnMouseMoved()
– setOnMousePressed()
– setOnMouseReleased()
●
Remember to import
– [Link].
JavaFX – Lambda Expressions
●
These methods use a special argument, called a Lambda
expression:
[Link]( /*Lambda Expression*/ );
●
Lambda expressions use special syntax:
(MouseEvent me) -> [Link]("Pressed")
●
Curley braces allow Lambda expressions to contain multiple
statements:
[Link]((MouseEvent me) -> {
[Link]("Statement 1");
[Link]("Statement 2");
});
JavaFX – Lambda Expressions as Arguments
● When these are combined, we get the following:
[Link]((MouseEvent me) -> {
[Link]("Statement 1");
[Link]("Statement 2");
});
●
What this code does:
– Allows imageView to detect a mouse press at any time.
– If that occurs, the two print statements are executed.
– Otherwise, this code is ignored.
JavaFX – MouseEvent
●
A MouseEvent object exists only within the scope of the Lambda
expression.
●
It contains many useful properties and methods:
[Link](me -> {
[Link]([Link]());
[Link]([Link]());
});
●
In this example:
– me is the MouseEvent object
– me is accessed to print the x and y positions of the mouse cursor when imageView
is pressed.
JavaFX – MouseEvent Methods
●
.getSceneX()
●
.getSceneY()
– Returns a double.
– Returns the position of the cursor within the JavaFX Scene.
– The top-left corner of the Scene is position (0,0).
●
.getScreenX()
●
.getScreenY()
– Returns a double.
– Returns the position of the cursor on your computer's screen.
– The top-left corner of your computer's screen is (0,0).
JavaFX – Event Listening
●
When you write code for MouseEvents.
– You're telling a Node to listen for a particular event.
– But the events don't actually have to occur.
●
As long as the Node is listening ....
– It can detect any event, at any time.
●
A Node can listen for many events.
[Link]( /* Lambda Expression */ );
[Link]( /* Lambda Expression */ );
[Link](/* Lambda Expression */ );
3rd lecture
●
Nested classes
●
Lambda expression
●
Generics
●
Wrapper classes
●
Java Collection Framework
06.10.2025 Java 1 190
Nested class
●
Global – could be qualified with name/instance of outer class.
– class,
– instance – inner classes.
●
Local – defined in block of code
– Named,
– Anonymous.
06.10.2025 Java 1 191
Global class nested types
public interface IMovable {
static public class MAdapter implements IMovable {
}
// ...
[Link] valN = new [Link]();
●
Class nested type is qualified with name of outer type – if is needed.
06.10.2025 Java 1 192
Instance of inner class contains
Inner classes reference to an instance of outer
public class OutterClass {
private int outerVal;
class.
public class InnerClass {
private int innerVal;
public void setVal(int val) {
[Link] = val; // accessing feature
// of outer class
[Link] = val + 1;// accessing feature of current class
}
}
public InnerClass getInstance() {
Instance of inner class could be
return new InnerClass(); in an instance method of outer
}
//...
class or with instance of outer
OutterClass val = new OutterClass(); class qualification.
[Link] val_i = [Link] InnerClass();
06.10.2025 Java 1 193
Local classes
●
When a class definition is local to public void moveDown() {
a block, it may access only Runnable run = new Runnable()
attributes and constants {
@Override
public void moveDown() { public void run() {
class MThread extends Thread { [Link]();
@Override }
public void run() { };
[Link]();
}
new Thread(run).start();
} }
new MThread().start();
}
06.10.2025 Java 1 194
Lambda expression
interface CheckPerson { printPersons(roster,
boolean test(Person p);
new CheckPerson() {
}
public static void printPersons(
public boolean test(Person p){
List<Person> roster, CheckPerson tester) { return [Link]() ==
for (Person p : roster) { [Link]
if ([Link](p)) { && [Link]() >= 18
[Link](); && [Link]() <= 25;
}
}
}
} });
printPersons(roster, (Person p) ->
[Link]() == [Link] && [Link]() >= 18 &&
[Link]() <= 25);
06.10.2025 Java 1 195
Lambda expression description
●
Substitutes syntax for a creation of anonymous classes where an
object of functional interface (interface having only one abstract
method defined) type is expected.
●
It is recommended to annotate a functional interfaces with the
annotation @FunctionalInterface. Compiler check whether it is
declared correctly.
06.10.2025 Java 1 196
Syntax of lambda expressions
●
A comma-separated list of formal parameters enclosed in
parentheses. (You can omit the data type of the parameters in a
lambda expression. In addition, you can omit the parentheses if
there is only one parameter. )
●
The arrow token, ->
p -> [Link]() == [Link]
&& [Link]() >= 18 && [Link]() <= 25
06.10.2025 Java 1 197
Syntax of lambda expressions II.
●
A body, which consists of a single expression or a statement block.
p -> [Link]() == [Link]
&& [Link]() >= 18 && [Link]() <= 25
p -> {
return [Link]() == [Link]
&& [Link]() >= 18 && [Link]() <= 25;
}
06.10.2025 Java 1 198
Syntax of lambda expressions III.
●
You do not have to enclose a void method invocation in braces.
email -> [Link](email)
06.10.2025 Java 1 199
Method References
●
a lambda expression does nothing but call an existing method - refer
to the existing method by name
[Link](rosterAsArray, (a, b) ->
[Link](a, b) );
[Link](rosterAsArray, Person::compareByAge);
06.10.2025 Java 1 200
Method References
Method Ref Type Example Lambda Equivalent
Static Integer::parseInt str -> [Link](str)
Instant then = [Link]();
Bound [Link]()::isAfter
t -> [Link](t)
Unbound String::toLowerCase str -> [Link]()
Class Constructor TreeMap<K,V>::new () -> new TreeMap<K, V>()
Array Constructor int[]::new len -> new int[len]
06.10.2025 Java 1 201
Generics
●
Known as parameterized types or templates.
●
Introduce parameters into class definition.
●
Benefits of generic types
– increased expressive power,
– improved type safety,
– explicit type parameters and implicit type casts.
06.10.2025 Java 1 202
Collections with generics
●
The main point: “old” containers List li = new ArrayList();
hold “Object” objects and need [Link]([Link](1));
casts which are problematic Integer x =
because cast is something the (Integer) [Link](0);
programmer thinks is true at a
single point.
List<Integer> li =
●
Generic type is true everywhere new ArrayList<>();
[Link]([Link](1));
Integer x = [Link](0);
06.10.2025 Java 1 203
Definition of generics
●
type variable = "placeholder" for class LinkedList<A> implements
an unknown type Collection<A> {
protected class Node {
A elt;
interface Collection<A> {
Node next = null;
public void add(A x);
public Iterator<A> iterator();
Node(A elt) {
}
[Link] = elt;
}
}
//...
06.10.2025 Java 1 204
Generics – type parameter bounds
●
bounds = super-type of a type public class TreeMap<
K extends Comparable, V> {
variable private static class Entry<K, V> {
– // ...
purpose: make available non- }
static methods of a type variable
– private Entry<K, V> getEntry(
limitations: gives no access to K key) {
constructors or static methods while (p != null) {
int cmp =
[Link]([Link]);
public interface // ...
}
Comparable<T> { // ...
public int compareTo(T arg); }
//...
} }
06.10.2025 Java 1 205
Generics – using generic types as variables
●
with specific type arguments
– specific instantiation
●
without type arguments
– raw type - no type argument specified, permitted for compatibility reasons,
permits mix of non-generic (legacy) code with a generic code
●
with wildcard arguments
– wildcard instantiation
06.10.2025 Java 1 206
Generics –wildcards
void printCollection(Collection<Object> c) {
for (Object o : c) {
[Link](o);
} // Collection<Object> is NOT supertype of any
} // other collection – this code is useless
/**
* The solution is wildcards.
*/
void printCollection(Collection<?> c) {
for (Object o : c) {
[Link](o);
}
}
06.10.2025 Java 1 207
Generics – bounded wildcards
●
unbounded wildcard -?
– all types
●
upper-bounded wildcard - ? extends Supertype
– all types that are subtypes of Supertype
– used for “Input” – where is value of a parameter type gained from an object
of generic type accessed as Supertype
●
lower-bounded wildcard - ? super Subtype
– all types that are supertypes of Subtype
– used for “Output” – where is value of a parameter type stored into an object
of generic type as Subtype
06.10.2025 Java 1 208
Generics methods
●
average() method signature:
static double average(List<? extends Number> nums)
●
Alternative (equivalent) signature:
static <T extends Number> double average(List<T> nums)
●
The latter is called a generic method.
●
Which is better?
– When there are no dependencies between the method parameters - use
wildcards.
06.10.2025 Java 1 209
Java Generics Implementation
●
The Java compiler translates generic code into pre-generic code by:
– Replacing every use of a formal type parameter by the use of the most
general type, it could be in context (trivially, Object)
●
This means that a code compiled with Java 5 can be run by the Java
1.4 Virtual machine –there is no change to the Java bytecode.
06.10.2025 Java 1 210
Wrapper classes
●
Generic types are limited for working with object types.
●
For every primitive type exists corresponding object type.
●
Java compiler converts between primitive type and its object
equivalent – if it is necessary.
06.10.2025 Java 1 211
Wrapper class
Double objectDoubleValue = 3.14e12;
double doubleValue = objectDoubleValue;
int intValue = [Link]();
boolean boolValue = [Link]("true");
Integer intObjectValue = [Link](150);
Integer intObjectValueFromString = [Link]("150");
06.10.2025 Java 1 212
List of wrapper classes
●
valueOf method – conversion Primitive Wrapper
class
Conversion method from string
from a primitive type or string boolean Boolean [Link](String s)
to object wrapper char Character …
byte Byte [Link](String s)
●
parseXXX method (e.g. [Link](String s, int radix)
parseFloat()) parse String and short Short [Link](String s)
[Link](String s, int
returns specific value as radix)
primitive type int Integer [Link](String s)
[Link](String s, int radix)
long Long [Link](String s)
●
xxxValue method (e.g. [Link](String s, int
floatValue()) returns the value radix)
float Float [Link](String s)
in a specific primitive type. double Double [Link](String s)
06.10.2025 Java 1 213
[Link] wrapper class
[Link](char c)
[Link](char c)
[Link](char c)
[Link](char c)
[Link](char c)
[Link](char c)
[Link](char c)
[Link](char c)
06.10.2025 Java 1 214
Java Collection Framework
06.10.2025 Java 1 215
Collections in Java
●
Collection (container)- objects that groups multiple elements into
single unit.
●
Collections Framework:
●
Interfaces – abstract data types representing collections
●
Implementations - concrete implementations of the interfaces –
general, legacy, special-purpose, concurrent, wrapper, abstract
●
Algorithms - methods that perform useful computations (searching
and sorting)
●
●
06.10.2025 Java 1 216
Collection types hierarchy
●
Extended from:
– [Link]
– [Link]
●
[Link] – not true collection but offers collection-like
manipulation
06.10.2025 Java 1 217
[Link] - hierarchy
Deque
06.10.2025 Java 1 218
[Link]
●
base interface
●
used to define a group of objects – allow manipulation, uniqueness
and ordering is not defined for the interface
●
methods:
– add(E), addAll(Collection<E>), remove(E), removeAll(Collection<E>),
clear(), retainAll(Collection<E>) – add/remove elements
– size():int, isEmpty():boolean – check number of elements
– contains (Object):boolean – check existence of element
– iterator() - returns new iterator – enable browsing
– toArray()
06.10.2025 Java 1 219
[Link]
●
ordered(defined index for every element) collection that may contain
duplicate elements
●
methods:
– <extends Collection>
– add(int,E), set(int,E), addAll(int,Collection<E>), get(int):E, remove(int):E –
add/remove elements to/from given position
– indexOf(Object):int, lastIndexOf(Object):int – find position of given object
– listIterator():ListIterator – return iterator that allows forward/backward
browsing
06.10.2025 Java 1 220
[Link]
●
collection of elements that does not contain duplicates
●
methods:
– <extends Collection>
– add(E):boolean, addAll(Collection<E>), contains(Object):boolean – added
constraints to inherited methods
06.10.2025 Java 1 221
[Link]
●
set of elements where is defined ordering (index for items are not
defined)
●
methods:
– <extends Set>
– comparator(): Comparator<E>
– subSet(E, E): SortedSet<E>
– headSet(E): SortedSet<E>
– tailSet(E): SortedSet<E>
– first(): E
– last(): E
06.10.2025 Java 1 222
Set implementation: HashSet, TreeSet
●
It is implemented by HashMap / TreeMap
06.10.2025 Java 1 223
[Link]
●
Queue is a list of elements with a first in first out ordering.
●
When you enqueue an element, it adds it to the end of the list.
●
When you dequeue an element, it returns the element at the front of
the list and removes that element from the list.
●
methods:
– <extends Collection>
– add(E), offer(E) – enqueue
– remove(): E, poll(): E – dequeue
– element():E, peek():E – retrieves but not remove
06.10.2025 Java 1 224
[Link]
●
double ended queue,
●
enables enqueue to the start and dequeue from the end,
●
provides stack functionality
●
methods:
– <extends Queue>
– addLast/addFirst; getLast/getFirst – manipulation with end or beginning
– push(E), pop(): E
– descendingIterator(): Iterator<E>
06.10.2025 Java 1 225
List implementation: ArrayList vs LinkedList
●
Definition: ●
Memory Usage:
– ArrayList: A resizable array implementation of – ArrayList uses less memory as it holds
the List interface. only data.
– LinkedList: A doubly-linked list – LinkedList uses more memory as it holds
implementation of the List and Deque data and two references for neighbor
interfaces. nodes.
●
Performance: ●
Use Case:
– ArrayList has a faster average time for – Use ArrayList when you have a fixed-size
accessing elements as it uses an index-based
system. list, and you know the size won't change.
– – Use LinkedList when you have to change
LinkedList has a faster average time for
adding and removing elements. the list size frequently by adding or
removing elements.
●
Syntax:
List<String> arrayList =
null prev prev prev prev
new ArrayList<>();
data data data data List<String> linkedList =
next next next next null
new LinkedList<>();
06.10.2025 Java 1 226
[Link]
●
base type for Collection
public interface Iterable<T> {
Iterator<T> iterator();
}
●
provides a comfort way for a loop construction – for-each
Iterable<String> values = new ArrayList<String>();
for (String string : values) {
06.10.2025 Java 1 227
Choose type of collection
●
choose more general type.
●
Iterable – only browsing (.. .and remove by iterator).
●
others – modification (add, remove), provide size information, check
existence of elements.
Ordered Indexed Unique FIFO LIFO
Collection
List Y Y
Queue Y Y
Deque Y Y Y
Set Y
OrderdSet Y Y
06.10.2025 Java 1 228
Map Y – by key Y – only key
[Link]
●
is a collection that links a key to a value.
●
cannot contains duplicates of key – each key can only exists once
and can only link to a single value.
●
for key and value could be used any type
Map<KeyType, ValueType> myMap;
06.10.2025 Java 1 229
[Link] - example
●
map String → Color
Map<String, Color> fruit2color = new HashMap<>();
●
insert pairs
[Link]("Apple", [Link]);
[Link]("Banana", [Link]);
[Link]("Mellone", [Link]);
●
get value for a specific key
Color colorOfBanana = [Link]("Banana");
Color colorOfApple = [Link]("Apple");
06.10.2025 Java 1 230
[Link] – another methods
●
containsKey(Object): boolean
●
containsValue(Object): boolean
●
keySet(): Set<K>
●
values(): Collection<V>
●
entrySet: Set<Entry<K,V>>
●
remove(Object): V
●
size(): int
06.10.2025 Java 1 231
Collection Implementations
Resizable Balanced Hash Table +
Interface Hash Table Linked List
Array Tree Linked List
Set HashSet TreeSet LinkedHashSet
Collection HashSet ArrayList TreeSet LinkedList LinkedHashSet
List ArrayList LinkedList
Queue ArrayDeque LinkedList
Deque ArrayDeque LinkedList
Map HashMap TreeMap LinkedHashMap
06.10.2025 Java 1 232
Requirements of using hash tables
●
classes of objects (value objects) stored in hash tables:
– objects stored in HashSet
– keys used with HashMap
●
should correctly override:
– hashCode
– equals (important also for comparison).
●
value object – instances where their identity is not important but
their state – String, Date, Money, Fraction, ComplexNumber…
●
06.10.2025 Java 1 233
hashCode method
●
provide Hash Function for
given object
●
for two objects representing the
same value must return same
result
●
for two objects representing
different values should return
different results – collisions are
sometimes necessary
●
06.10.2025 Java 1 234
equals method
●
used for distinguishing
between object targeting the
same bucket
●
for two objects representing the
same value must return true
●
for two objects representing
different values must return
false
●
used also in implementation of
method contains (declared in
Collection)
●
06.10.2025 Java 1 235
Map implementation: HashMap vs TreeMap
● Definition:
– HashMap: Part of Java's collection since Java 1.2, provides the basic implementation
of Map interface by hash table
– TreeMap: A Red-Black tree based NavigableMap implementation, sorted according to
the natural ordering of its keys.
● Performance:
– HashMap generally offers constant time performance for the basic operations — get
and put.
– TreeMap guarantees log(n) time cost for the containsKey, get, put, and remove
operations.
● Ordering:
– HashMap does not maintain any order of its keys.
– TreeMap maintains ascending order of its keys.
● Null Keys and Values:
– HashMap allows one null key and multiple null values.
– TreeMap does not allow null keys but may contain multiple null values.
● Use Case:
– Use HashMap when you do not need sorted keys, and you need better performance.
– Use TreeMap when you need sorted keys, and you can compromise on performance
for ordering.
● Syntax:
Map<String, String> hashMap = new HashMap<>();
Map<String, String> treeMap = new TreeMap<>();
06.10.2025 Java 1 236
Algorithm
●
Class “[Link]”
– Sorting
– Shuffling
– Routine data manipulation
– Searching
– Composition
– Finding extreme values
06.10.2025 Java - EFREI 237
Some useful interfaces - comparing
●
We often need to compare objects of the same type (class or
interface) with each other. According to ordering.
●
Comparable / Comparator
06.10.2025 Java - EFREI 238
Comparable
●
Comparable object can itself public interface Comparable<T> {
compare with another object of public int compareTo(T t);
}
the same type.
Returns:
●
-1 or int less then zero if this < t
public class ComparingIntegers {
public static void main(String[] args) {
Integer int_10 = 10;
●
1 or int bigger then zero if this > t
Integer int_100 = 100;
Integer int_1000 = 1000;
●
0 if this == t
[Link]("CompareTo result : " + int_10.compareTo(int_100));
// displays -1 because 10 < 100
[Link]("CompareTo result : " + int_1000.compareTo(int_100));
// displays 1 because 1000 > 100
[Link]("CompareTo result : " + int_100.compareTo(int_100));
// displays 0 because 100 == 100
}
}
06.10.2025 Java - EFREI 239
Comparator
●
if we want to have several ways public interface Comparator<T> {
of comparing, we cannot int compare(T o1, T o2);
}
implement the Comparable
interface several times !
Returns:
●
Define a comparator once, and ●
-1 or int less then zero if o1 < o2
use it everywhere! ●
1 or int bigger then zero if o1 > o2
●
Comparator object can ●
0 if o1 == o2
compare two objects of the
same type
06.10.2025 Java - EFREI 240
Algorithm – sorting – Comparable/Comparator using
List of comparable objects
public static <T extends Comparable<? super T>> void sort(List<T> list)
List<Double> listToSort = new ArrayList<>();
//fill list with data
[Link](listToSort);
List of non-comparable objects
public static <T> void sort(List<T> list, Comparator<? super T> c)
List<Rectangle> listToSort = new ArrayList<>();
// fill list with data
[Link](listToSort, new Comparator<Rectangle>() {
@Override
public int compare(Rectangle o1, Rectangle o2) {
return [Link]() * [Link]()
- [Link]() * [Link]();
}
});
06.10.2025 Java - EFREI 241
Algorithm – shuffling, data manipulation
●
shuffling
– void shuffle(List<?> list)
– void shuffle(List<?> list, Random rnd)
●
data manipulation
– void swap(List<?>, int i, int ii)
– <T> void fill(List<? super T> list, T obj)
– <T> void copy(List<? super T> dest, List<? extends T> src)
– void reverse(List<?> list)
– <T> boolean addAll(Collection<? super T> c, T... elements)
06.10.2025 Java - EFREI 242
Algorithm – Searching, Composition, Finding Extreme
values
●
Searching
– int binarySearch(List<? extends Comparable<? super T>> list, T key)
– int binarySearch(List<? extends T> list, T key, Comparator<? super T> c)
●
Composition
– int frequency(Collection<?> c, Object o)
– boolean disjoint(Collection<?> c1, Collection<?> c2)
●
Finding Extreme Values
– <T extends Comparable> T max(Collection<? extends T> coll)
– <T> T max(Collection<? extends T> coll, Comparator<? super T> comp)
– <T extends Comparable> T min(Collection<? extends T> coll)
– <T> T min(Collection<? extends T> coll, Comparator<? super T> comp)
06.10.2025 Java - EFREI 243
4th lecture
●
Exceptions
●
I/O streams in Java
●
File I/O
●
String and StringBuilder
●
Regular expressions
06.10.2025 Java 1 244
Exceptions
06.10.202 Java 1 245
5
Handling of exceptional situations in Java
●
Java uses system of exceptions as many other programming
languages:
– C++
– C#
– Python
– PHP
– Ruby
06.10.2025 Java 1 246
Technics to indicate that an error occured
●
diagnostic return value
– Test the return value.
●
Attempt recovery on error.
●
Avoid program failure.
– Ignore the return value.
●
Cannot be prevented.
●
Likely to lead to program failure.
●
exception throwing (preferred)
– Handle exception
– Pass exception to another block of code where it should be handled
06.10.2025 Java 1 247
Exception-throwing principles
●
Directly implemented in a language
●
No ‘special’ return value needed.
●
The normal flow-of-control is interrupted.
●
Special recovery actions are supposed.
●
Thrown exception cannot be ignored in the client object
06.10.2025 Java 1 248
How is an exception thrown
●
An object representing an exception is constructed:
new ExceptionType("...")
●
The keyword “throw” is used to throw the exception object:
throw new ExceptionType("a error message");
●
If the method throws an exception outside, then it is specified in
Javadoc documentation:
@throws ExceptionType reason description
●
An exception should be also thrown by Virtual machine internally
(division by zero value)
06.10.2025 Java 1 249
Exceptions
●
Its throwing indicates an exceptional situation,
●
any instance of class inherited from Throwable
●
important examples: IllegalArgumetnException,
IllegalStateException, NullPointerException,
IndexOutOfBoundException, RuntimeException
// immediate exception throwing
throw new IllegalArgumentException();
// exception could be throwed later
IllegalArgumentException e = new IllegalArgumentException();
throw e;
06.10.2025 Java 1 250
Overview of an exception class hierarchy
Throwable Standard library classes
User defined classes
Error Exception
MyCheckedException RuntimeException
MyUncheckedException
06.10.2025 Java 1 251
Main exception categories
●
Checked exceptions
– Subclass of Exception
– Used for anticipated failures.
– Where recovery may be possible.
– Should be handled in a method when raises or the method should be
marked
●
Unchecked exceptions
– Subclass of RuntimeException
– Used for unanticipated failures.
– can raise uncontrollably from a method
06.10.2025 Java 1 252
What exceptions does Java throw to us
●
Error – InternalError, OutOfMemoryError, VirtualMachineError,
StackOverflowError.
●
Exception
– unchecked- RuntimeException and its successor
●
ArithmeticException, IllegalArgumentException, UnsuportedOperationException,
IllegalStateException,…
– checked – other successor of Exception
●
ClassNotFoundException, DataFormatException, InterruptedException,
IOException.
06.10.2025 Java 1 253
The effect of an exception
●
The throwing method finishes exceptionally.
●
The throwing method returns no value.
●
Control does not return after the point of method call.
●
A client must/may handle an exception.
06.10.2025 Java 1 254
Unchecked exceptions
●
Compiler doesn’t check these exceptions
●
It causes program termination if not handled.
●
NotSupportedException is a typical example.
06.10.2025 Java 1 255
Example of an unchecked exception
public void setDimension(int width, int height) {
if ((width < 0) || (height < 0)) {
throw new IllegalArgumentException(
"Dimension should be greater or equal to 0:
width=" + width + ", height = " + height);
}
erase();
[Link] = width;
[Link] = height;
paint();
}
06.10.2025 Java 1 256
Exception handling
●
Checked exceptions are perceived to be caught and eventually
handled.
●
The compiler ensures that their use is strictly controlled.
●
Used carefully, failures may be recoverable.
06.10.2025 Java 1 257
Example of block with an exception
try {
// critical section
} catch (IllegalArgumentException e) {
// handle exception o type IllegalArgumentException
} catch (NullPointerException | IOException e) {
// handle exception o type NullPointerException and IOException
} catch (Throwable e) {
// handle every exception – object o type Throwable
} finally {
// this block is always performed when the critical section is
leaved
}
06.10.2025 Java 1 258
Throws clause
●
Methods that can propagate a checked exception must be marked with throws clause:
/**
*
* @param fileName
* @return
* @throws IOException
*/
public String filterInputFile(String fileName) throws IOException {
InputStream is = new FileInputStream(fileName);
StringBuilder sb = new StringBuilder();
int chars;
byte[] buffer = new byte[1024];
while (-1 != (chars = [Link](buffer))) { Every checked exception should be
[Link](new String(buffer, 0, chars)); handled in the method or the method
} specifies exception throwing.
[Link]();
return [Link]();
}
06.10.2025 Java 1 259
try statement
●
The source code catching an exception must surround the call with
the try statement:
try {
// this section contains commands that are
// source of exception throwing
} catch (Exception e) {
// caught exception is handled here,
// it is accessible as variable with name e
}
06.10.2025 Java 1 260
try statement 1. Exception thrown from this method
try {
[Link](fileName);
//some following code
} catch(IOException e) {
[Link]("Unable to process file "
+ fileName + "exception thrown: "
+ [Link]());
}
2. Control moves here
06.10.2025 Java 1 261
Catching multiple exceptions
try {
// block of code that should throw exceptions
FileInputStream fis = new FileInputStream("[Link]");
// file processing
} catch (EOFException e) {
// Take action on an end-of-file exception.
} catch (FileNotFoundException e) {
// Take action on a file-not-found exception.
}
06.10.2025 Java 1 262
Handling different exceptions by same code block
try {
// block of code that should throw exceptions
FileInputStream fis = new FileInputStream("[Link]");
// file processing
} catch (EOFException | FileNotFoundException e) {
// Take action on an end-of-file and
// file-not-found exception.
}
06.10.2025 Java 1 263
Finally clause
●
The finally clause is executed even if a return statement is executed in the
try or catch clauses.
●
An uncaught or propagated exception still exits via the finally clause.
try {
//Protect one or more statements here.
} catch (Exception e) {
//Report and recover from the exception here.
} finally {
//Perform any actions here common to whether or not
//an exception is thrown.
}
06.10.2025 Java 1 264
Exception conversion
●
Used when we need propagate a different exception type from a method
●
Often used to the conversion into the RuntimeException or another
unchecked exception
●
Add useful information what's wrong
●
Good practices is wrap original exception (use it as constructor parameter)
try {
// ...
} catch (IOException e) {
throw new MyException(e);
}
06.10.2025 Java 1 265
Features of exceptions
●
methods:
– getMessage
– toString
– printStackTrace
– printStackTrace(PrintStream)
06.10.2025 Java 1 266
Defining new exception types
●
Extend RuntimeException for an unchecked or Exception for a
checked exception.
●
We use our exception type to improve diagnostic information.
– It can contain additional reporting and/or recovery information.
06.10.2025 Java 1 267
Defining new exception types in an action
public class NotConnectedException extends Exception {
private String host;
public NotConnectedException(String address) {
super("Host: " + address + " is not accesible");
host = address;
}
public String getHost() {
return host;
}
@Override
public String toString() {
return "NotConnectedException [host=" + host
+ ", getMessage()=" + getMessage() + "]";
}
}
06.10.2025 Java 1 268
Error recovery
●
Clients should take description of error notifications.
– After method calling, it checks the method return values.
– Exceptions should not be ‘ignored’.
●
Client code usually attempts to recover.
– It is often implemented in a loop.
06.10.2025 Java 1 269
Attempting recovery
// Try to connect to server.
boolean successful = false;
int attempts = 0;
do {
try {
[Link]();
successful = true;
}
catch(TimeoutException e) {
[Link]("Unable connect to " + server);
attempts++;
if(attempts < MAX_ATTEMPTS) {
server = getAlternativeServer(server);
}
}
} while(!successful && attempts < MAX_ATTEMPTS);
if(!successful) {
//Report the probslem and give up;
}
06.10.2025 Java 1 270
Enhanced syntax of “try” - motivation
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("filename"));
[Link]();
} catch (FileNotFoundException e) {
// the specified file could not be found
} catch (IOException e) {
// something went wrong with reading
} finally {
try {
if (reader != null)
[Link]();
} catch (IOException e) {
// something went wrong with closing
}
}
06.10.2025 Java 1 271
Enhanced syntax of “try”
try (BufferedReader reader =
new BufferedReader(new FileReader("filename"))) {
String line = null;
while (null != (line = [Link]())) {
// do something with line
}
} catch (FileNotFoundException e) {
// the specified file could not be found
} catch (IOException e) {
// something went wrong with reading
}
06.10.2025 Java 1 272
Enhanced syntax of “try” - usage
●
It can be used on any class that implements interface
AutoCloseable
public interface AutoCloseable {
void close() throws Exception;
}
06.10.2025 Java 1 273
I/O in Java
●
I/O streams - read/write data from/to file, network, memory –
classes mainly in package [Link]
●
File I/O - file system operations – check files, directories, delete,
create, move – classes mainly in package [Link]
●
06.10.2025 Java 1 274
I/O streams - outline
●
Byte and character stream
●
Line orientation
●
Scanning, formatting
●
Additional streams – buffered, data, object
●
Stream wrapping concept
06.10.2025 Java 1 275
I/O Streams
●
represents input (source) and output (destination) – disk files,
devices, other programs (also on different computers), memory
arrays.
●
support many kinds of data – bytes, primitive types, localized
characters, objects
●
some simply pass data, some do transformations
06.10.2025 Java 1 276
I/O streams II.
●
input streams - used for read
data from source
●
output streams – used for
write data to destination
06.10.2025 Java 1 277
Byte streams
InputStream
●
I/O of 8-bit bytes
●
read():int ●
derived from InputStream and OutputStream
●
read(byte[]):int
●
read(byte[],int,int):int
●
available():int OutputStream
●
skip(long):long
●
write(int):void
●
mark(int): void ●
write(byte[]):void
●
reset():void ●
write(byte[],int,int):void
●
markSupported():boolean ●
flush():void
●
close():void ●
close():void
06.10.2025 Java 1 278
Byte streams – copy byte by byte
public static void main(String[] args)
throws FileNotFoundException, IOException {
try (InputStream in = new FileInputStream("[Link]");
OutputStream out = new FileOutputStream("[Link]")) {
int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
}
}
06.10.2025 Java 1 279
Byte streams – copy with buffer
private static final int SIZE_OF_BUFFER = 1024;
public static void main(String[] args)
throws FileNotFoundException, IOException {
try (InputStream in = new FileInputStream("[Link]");
OutputStream out = new FileOutputStream("[Link]")) {
int count;
byte[] buffer = new byte[SIZE_OF_BUFFER];
while ((count = [Link](buffer)) != -1) {
[Link](buffer, 0, count);
}
}
}
06.10.2025 Java 1 280
Byte streams – using
●
always close (if not used)
●
low-level I/O
●
other streams built on byte streams (even character)
06.10.2025 Java 1 281
Character streams
Reader Writer ●
I/O of character data
●
read(CharBuffer):int ● write(int):void
●
read():int ●
write(char[]):void
●
translates between
●
read(char[]):int ●
write(char[],int,int):void character data encoded in
●
read(char[],int,int):int ● write(String, int, int ):void local character
●
skip(long): long
●
append(CharSequence): set(windows 1250, iso
Writer
●
ready(): boolean ●
append(CharSequence,int
8859-2, ..) and internal
●
mark(int): void ,int):Writer format (UTF-8)
●
reset():void ●
append(char):Writer
flush():void
●
derived from Reader and
markSupported():boo
● ●
lean ●
close():void Writer
●
close():void
06.10.2025 Java 1 282
Character streams – copy char by char
public static void main(String[] args)
throws FileNotFoundException, IOException {
try (Reader in = new FileReader("[Link]");
Writer out = new FileWriter("[Link]")) {
int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
}
}
06.10.2025 Java 1 283
Character streams – copy with buffer
private static final int SIZE_OF_BUFFER = 1024;
public static void main(String[] args)
throws FileNotFoundException, IOException {
try (Reader in = new FileReader("[Link]");
Writer out = new FileWriter("[Link]")) {
int count;
char[] buffer = new char[SIZE_OF_BUFFER];
while ((count = [Link](buffer)) != -1) {
[Link](buffer, 0, count);
}
}
}
06.10.2025 Java 1 284
Line-Oriented I/O
●
process character streams based on line
●
[Link], [Link]
●
BufferedReader extends Reader and wrap another Reader
●
PrintWriter extends Writer and wrap another Writer
try (
BufferedReader in = new BufferedReader(new FileReader("[Link]"));
BufferedWriter out = new BufferedWriter(new FileWriter("[Link]")))
{
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
}
06.10.2025 Java 1 285
Buffered Streams
●
add buffering functionality to other streams – by wrapping them
Reader rd = new BufferedReader(new FileReader("[Link]"));
●
BufferedInputStream, BufferedOutputStream
●
BufferedReader, BufferedWriter
●
method flush forces writing before filling buffer
●
06.10.2025 Java 1 286
Scanning
●
comfort way to read structured text data as tokens
●
class Scanner:
– can be constructed from: Readable(interface – Reader implements),
InputStream, File, Path, ReadableByteChannel
– methods: next, nextLine, nextByte(Int,…), hasNext, hasNext<XXX>
– support locale settings – delimiters,
06.10.2025 Java 1 287
Formatting
●
PrintWriter (Writer) or PrintStream (Stream)
●
available methods – print(<type>), println(<type>), printf (format)
●
PrintWriter preffered over PrintStream (use only [Link])
[Link]("%f, %1$+020.10f", 10.f,[Link]);
06.10.2025 Java 1 288
Data Streams
●
supports binary I/O of primitive data type values and Strings
●
interface DataOutput, DataInput – implemented by DataOuputStream,
DataInputStream
●
they are used again as wrappers of byte streams
DataInputStream dis = new DataInputStream(new
FileInputStream("[Link]"));
●
these classes extends InputStream (and OutputStream) and add methods:
●
writeDouble – readDouble
●
writeInt – readInt
●
writeUTF – readUTF
●
writeBytes(), writeChars() - readLine()
●
write<xxx> - read<xxx>
●
06.10.2025
● Java 1 290
Object Streams - serialization
// Write objects //Read objects
Counter counter = new Counter(0); FileInputStream f = new
// ... FileInputStream("[Link]");
FileOutputStream f = new ObjectInput input = new
FileOutputStream("[Link]"); ObjectInputStream(f);
ObjectOutput output = new
ObjectOutputStream(f); Counter counter = (Counter)
[Link](counter); [Link]();
[Link]([Link]()); LocalDate date = (LocalDate)
[Link]();
●
The capability to store and retrieve Java objects is essential to building all but the
most transient applications. The key to storing and retrieving objects is
representing the state of objects in a serialized form sufficient to reconstruct the
object(s). Objects to be saved in the stream may support either the Serializable or
the Externalizable Interface
06.10.2025 Java 1 291
Objects Streams – storing of references
●
they can store complex structure of objects connected by references
– it can handle also loops
●
every stored object have to be Serializable or Externalizable
06.10.2025 Java 1 292
Transient attributes
●
Attributes marked as a transient are not saved during serialization.
public class Car implements Serializable {
// State variables
private int speed;
private String type;
transient private String accessCode;
}
[Link](car); car = (Car)[Link]();
speed 100 speed 100
color “RED“ color “RED“
accessCode “123456“ accessCode null
06.10.2025 Java 1 293
Wrapping of streams
●
general and fundamental principle of I/O streams
●
source/destination – FileInputStream, FileOutputStream, FileReader,
FileWriter,[Link]
●
additional functions:
– buffering – BufferedInputStream, BufferedOutputStream, BufferedReader, BufferedWriter
– decompression/ compression – GZipInputStream(and output)
– decryption/encryption – CipherInputStream,...Output…
– convert byte stream to character – InputStreamReader,Output..Writer
– …..
●
additional methods for reading/writing – BufferedReader. PrintWriter
PrintWriter pw = new PrintWriter(
new OutputStreamWriter(
new GZIPOutputStream(
new CipherOutputStream(
new FileOutputStream("[Link]"), ciper))));
06.10.2025 Java 1 294
File I/O
●
since JDK 1.7 – [Link]
●
access to file system
●
type Path – representation of path to file or directory
●
class Files – file system operations
06.10.2025 Java 1 295
Path
●
identification of file or directory in hierarchical file system
●
absolute or relative – d:\data\movies, files\music
●
symbolic links
06.10.2025 Java 1 296
Type Path - operations
●
Creating a Path – [Link](pathName)
●
Retrieving Information – methods:
●
getFileName, getName(int), getNameCount(), subpath(int,int), getParent(),
getRoot()
●
Remove Redunancies - /home/./joe/foo
– normalize,
●
Converting Path – methods:
– toUri():URI
– toAsolutePath():Path,
– toRealPath(LinkOption):Path – can resolve symbolic links (NOFOLLOW_LINKS),
return absolute, remove redundancies
– toFile()
●
06.10.2025 Java 1 297
Checking a File or Directory - static methods in Files
●
verify existence – exists(), notExists(), isSymbolicLink(),
isDirectory(), isRegularFile()
●
checking file accessibility – isReadable(), isWritable(),
isExecutable()
●
[Link]()
●
06.10.2025 Java 1 298
Delete, copy and move files and directories
●
delete:
– [Link](Path) – throws NoSuchFileException;
– [Link](Path)
●
copy:
– [Link](Path, Path, CopyOption ..),
– [Link](InputStream, Path, CopyOption ..),
– [Link](Path, OutputStream)
●
[Link](Path, Path, CopyOption ..)
06.10.2025 Java 1 299
Managing Metadata - static methods in Files
●
size(Path)
●
isDirectory(Path, LinkOption) ,isRegularFile(Path, LinkOption…),
isSymbolicLink(Path)
●
isHidden(Path)
●
getLastModifiedTime(Path, LinkOption…), setLastModifiedTime(Path,
FileTime)
●
getOwner(Path, LinkOption…), setOwner(Path, UserPrincipal)
●
getPosixFilePermissions(Path, LinkOption…),
setPosixFilePermissions(Path, Set<PosixFilePermission>)
●
getAttribute(Path, String, LinkOption…), setAttribute(Path, String, Object,
LinkOption…)
●
readAttrbiutes – bulk operation
●
06.10.2025 Java 1 300
Reading, Writing, and Creating Files
●
alternate to FileInputStream, FileOutputStream
●
several has OpenOptions:
– WRITE, APPEND, TRUNCATE_EXISTING, CREATE_NEW, CREATE,
DELETE_ON_CLOSE, SPARSE, SYNC, DSYNC
06.10.2025 Java 1 301
Creating special files
●
empty files:
– createFile(Path, FileAttribute<?>)
●
temp files:
– createTempFile(Path, String, String, FileAttribute<?>)
– createTempFile(String, String, FileAttribute<?>)
06.10.2025 Java 1 302
Other file I/O functionality
●
Random Access File – ●
Links – symbolic, hard – create,
SeekableByteChannel detect, find target
●
Creating and Reading Directories: ●
Walking the File Tree
– createDirectory(Path, FileAttribute<? ●
Finding Files
>)
– createDirectories(Path,
●
Watching a Directory for Changes
FileAttribute<?>) ●
Other methods – Determine MIME
– createTempDirectory(Path, String, Type, Dafault File System, Path
FileAttribute<?>...) Sring Separator, Store
– createTempDirectory(String, ●
Replace and extends functionality
FileAttribute<?>…)
offered by [Link]
– listing
06.10.2025 Java 1 303
Summary of file I/O
●
core is package [Link]:
– Path - has methods for manipulating a path.
– Files - has methods for file operations, such as moving, copy, deleting, and
also methods for retrieving and setting file attributes.
– FileSystem - has a variety of methods for obtaining information about the
file system.
●
Other advanced concepts – not covered:
– buffer orientation
– non blocking I/O
– selectors
06.10.2025 Java 1 304
References
●
Oracle tutorial:
[Link]
06.10.2025 Java 1 305
String – immutable object
●
A String object is immutable; that, after a String object is created,
its value can’t be changed.
●
Because string are immutable, Java can process them very
efficiently –it is possible share same object among variables
(remember Java use it during string literal creation)
●
Every method called to String object doesn’t modify the object – new
one is created instead.
●
Immutable objects are suggested design decision in case of value
objects (currency, complex numbers,…).
06.10.2025 Java 1 306
StringBuilder Objects can be modified
●
It is not possible to make modifications to a String.
●
Methods used to “modify” a String actually create a new String in
memory with the specified changes, they do not modify the old one.
●
This is why StringBuilders are much faster to work with: They can
be modified and do not require you to create a new String with each
modification.
06.10.2025 Java 1 307
StringBuilder and String Shared Methods
●
StringBuilder shares many of the same methods with String, including but not
limited to:
– charAt(int index)
– indexOf(String str)
– Length()
– substring(int start, int end)
// shared StringBuilder and String methods
[Link]("The length of the text is: " + [Link]());
[Link]("The character at the beginning is: " + [Link](0));
[Link]("The second character is: " + [Link](1));
[Link]("The position of the start of the text \"acl\" is: "
+ [Link]("acl"));
[Link]("The following text is included within the String: "
+ [Link](1, 4));
06.10.2025 Java 1 308
StringBuilder Methods
●
StringBuilder also has some methods specific to its class, including
the five below:
Method Description
append(Type t) ls compatible with any Java type or object, appends the String
representation of the Type argument to the end of the sequence.
delete(int start, int end) Removes the character sequence included in the Substring from start to
end.
insert(int offset, Type t) ls compatible with any Java type, inserts the String representation of Type
argument into the sequence.
replace(int start, int end, String Replaces the characters in a Substring of this sequence with characters in
str) str.
reverse() Causes this character sequence to be replaced by the reverse of the
sequence.
06.10.2025 Java 1 309
StringBuilder versus String
●
These are some of the important differences between a StringBuilder
and a String object.
StringBuilder String
Changeable Immutable
Easier insertion, deletion, and replacement. Easier concatenation.
Can be more difficult to use, especially when Visually simpler to use, similar to primitive
using regular expressions (introduced in the types rather than objects.
next lesson).
Use when memory needs to be conserved. Use with simpler programs where memory is
not a concern.
06.10.2025 Java 1 310
Regular Expressions
●
A regular expression is a character or a sequence of
●
characters that represent a String or multiple Strings.
●
Regular expressions:
– Are part of the [Link] package, thus any time regular expressions
are used in your program you must import this package.
– Syntax is different than what you are used to but allows for quicker, easier
searching, parsing, and replacing of characters in a String.
06.10.2025 Java 1 311
[Link](String regex)
●
The String class contains a method named matches(String regex)
that returns true if a String matches the given regular expression.
●
This is similar to the String method equals(String str).
●
The difference is that comparing the String to a regular expression
allows variability.
●
For example, how would you write code that returns true if the String
animal is “cat” or “dog” and returns false otherwise?
06.10.2025 Java 1 312
Equals Versus Matches
●
Astandard answer may look something like this:
if ([Link]("cat"))
return true;
else if ([Link]("dog"))
return true;
return false;
●
An answer using regular expressions would look something like this:
return [Link]("cat|dog");
●
The second solution is much shorter. The regular expression symbol
| allows for the method matches to check if animal is equal to “cat” or
“dog” and return true accordingly.
06.10.2025 Java 1 313
Square Brackets
●
Square brackets are used in regular expression to allow for
character variability.
●
If you wanted to return true if animal is equal to “dog” or “Dog”, but
not “dOg”, using equalslgnoreCase() would not work and using
equals would take time and multiple lines.
●
If you use regular expression, this task can be done in one line as
follows.
●
This code tests if animal matches “Cat” or “cat” or “Dog” or “dog” and
returns true if it does.
return [Link]("[Cc]at| [Dd]og");
06.10.2025 Java 1 314
Using Square Brackets and a Hyphen
●
To allow the first character to be any number or a space in addition
to a lower or upper case character, simply add “ 0-9” inside the
brackets (note the space before 0).
return [Link]("[ 0-9a-zA-Z]ouse");
06.10.2025 Java 1 315
Other elements in a regular expression
●
The dot (.) – represents any character: “[0-9].”
Repetitions
●
* – 0..N: “A*”
●
? – 0..1: “A?”
●
+ – 1..N: “A+”
●
{x} – x: “A{7}”
●
{x,y} – x..y:“A{7,9}”
●
{x,} – x..N: “A{5,}”
●
06.10.2025 Java 1 316
Pattern
●
A Pattern is a class in the [Link] package that stores the
format of the regular expression.
●
For example, to initialize a Pattern of characters as defined by the
regular expression “[A-F]{5,}.*” you would write the following code:
Pattern p = [Link]("[A-F]{5,}.*");
●
The compile method returns a Pattern as defined by the regular
expression given in the parameter.
06.10.2025 Java 1 317
Matcher
●
A matcher is a class in the [Link] package that stores a
possible match between the Pattern and a String.
●
A Matcher is initialized as follows:
Pattern patternName = [Link]("[A-Z][a-z]+");
Matcher match = [Link]("David");
●
The matcher method returns a Matcher object.
●
The following code returns true if the regular expression given in the
Pattern patternName declaration matches string.
[Link]();
06.10.2025 Java 1 318
Matcher: Putting it All Together
import [Link];
import [Link];
public class PatternTest {
public static void main(String[] args) {
Pattern p = [Link]("[A-F]{5,}.*");
String str = "AAAAAhhh";
boolean matched = isMatch(str, p);
[Link](matched);
}
private static boolean isMatch(String str, Pattern p) {
Matcher match = [Link](str);
return [Link]();
}
}
06.10.2025 Java 1 319
Benefits to Using Pattern and Matcher
●
This seems like a very complex way of completing the same task as
the String method matches.
●
Although that may be true, there are benefits to using a Pattern and
Matcher such as:
– Capturing groups of Strings and pulling them out, allowing to keep specific
formats for dates or other specific formats without having to create special
classes for them.
– Matches has a find() method that allows for detection of multiple instances
of a pattern within the same String.
06.10.2025 Java 1 320
Regular Expressions and Groups
●
Segments of regular expressions can be grouped using
●
parentheses, opening the group with “(“ and closing it with “)“.
●
These groups can later be accessed with the Matcher method
group(groupNumber).
●
For example, consider reading in a sequence of dates, Strings in the
format “DD/MM/YYYY”, and printing out each date in the format
“MM/DD/YYYY”.
●
Using groups would make this task quite simple.
06.10.2025 Java 1 321
Regular Expressions and Example
Group 1 Group 2 Group 3
Pattern dateP = [Link]("([0-9]{2})/([0-9]{2})/([0-9]{4})");
Scanner in = new Scanner([Link]);
[Link]("Enter a Date (dd/mm/yyyy): "); Recalls each group of
String date = [Link](); the Matcher.
while () {
Matcher dateM = [Link](date);
if ([Link]()) {
String day = [Link](1); Group 1 and Group 2 are defined to
String month = [Link](2); consist of 2 digits each. Group 3 (the
String year = [Link](3); year) is defined to consist of 4 digits.
[Link]("US style date - " Note: It is still possible to get the whole
+ month + "/" + day + "/" + year); Matcher by calling group (0).
}
[Link]("Enter a Date (dd/mm/yyyy): ");
date = [Link]();
}
06.10.2025 Java 1 322
[Link]()
●
Matcher's find method will return true if the defined Pattern exists as
a Substring of the String of the Matcher.
●
For example, if we had a pattern defined by the regular expression
“[0-9]”, as long as we give the Matcher a String that contains at least
one digit somewhere in the String, calling find() on this Matcher will
return true.
06.10.2025 Java 1 323
Example code for find
Scanner sc = new Scanner([Link]);
String line;
Pattern pattern = [Link]("([0-9]{2})/([0-9]{2})/([0-9]
{4})");
while ((line = [Link]()) != null) {
Matcher matcher = [Link](line);
while ([Link]()) {
int day = [Link]([Link](1));
int month = [Link]([Link](2));
int year = [Link]([Link](3));
[Link]("%d.%d.%d", day, month, year);
}
}
06.10.2025 Java 1 324
Parsing a String with Regular Expressions
●
Recall the String method split() introduced earlier in the lesson,
which splits a String by spaces and returns the split Strings in an
array of Strings.
●
The split method has an optional parameter, a regular expression
that describes where the operator wishes to split the String.
●
For example, if we wished to split the String at any sequence of one
or more digits, we could write something like this:
String[] tokens = [Link]("[0-9]+");
06.10.2025 Java 1 325
Replacing with Regular Expressions
●
There are a few simple options for replacing Substrings using
regular expressions.
●
The following is the most commonly used method.
●
replaceAll - For use with Strings, the method:
[Link]("RegularExpression", newSubstring);
●
replaceAll will replace all occurrences of the defined regular
expression found in the String with the defined String newSubstring.
●
Other methods that could be used are replaceFirst() and split() that
can be both be researched through the Java API.
06.10.2025 Java 1 326
Replacing using a Matcher
●
replaceAll - For use with a matcher
●
This method works the same if called by a Matcher rather than a
String. However, it does not require the regular expression.
●
It will simply replace any matches of the Pattern you gave it when
you initialized the Matcher.
●
The method example shown below results in a replacement of all
matches identified by Matcher with the String “abc”.
[Link]("abc");
06.10.2025 Java 1 327
5th lecture
●
JDBC – Java API for DBMS
●
Case study – JDBC, TableView
●
Java SE 8 Streams
●
Date and Time in Java since version 8
●
XML
●
JSON
●
Networking
06.10.2025 Java 1 328
JDBC API
●
Java API that can access any kind of tabular data – stored mainly in
Relational Database
●
SQL – language for manipulation
●
JDBC API
– Establishing connection with database
– Creating and sending SQL statement to database
– Retrieving and process result of SQL query
●
[Link]
06.10.2025 Java 1 329
JDBC – Architecture aJava
Applet/Application
JDBC API
JDBC Driver Manager/
DataSource Object
Pure Java JDBC Pure Java JDBC
Driver Driver
DB Middleware
DB
DB
Server
Server
06.10.2025 Java 1 330
JDBC example
●
Connect to a data source, like a database.
●
Send queries and update statements to the database.
●
Retrieve and process the results received from the database in reply to
your query.
Connection con = [Link]("jdbc:myDriver:myDB",
"myLogin", "myPassword");
Statement stmt = [Link]();
ResultSet rs = [Link]("SELECT a, b, c FROM Table1");
while ([Link]()) {
int x = [Link]("a");
String s = [Link]("b");
float f = [Link]("c");
}
[Link]();
06.10.2025 Java 1 331
JDBC Drivers
• Types:
– JDBC – ODBC bridge driver
– Java and native code Driver
– Pure Java Driver – communication with database server
– Pure Java Driver – communicate with middleware server
• Concrete drivers for common database systems
– MySQL Connector/JDBC
• [Link]
– [Link]
– Oracle Database 11g R2 JDBC driver
• [Link]
– JavaDB – distribution of Apache Derby database
• Included in JDK from version 7
• Written completely in Java
– MSSQL, …
• Obtained driver library must be linked to Java application in same way as other used libraries.
06.10.2025 JAT - Java Technologie 332
JDBC – Driver Initialization
Using DriverManager
try {
[Link]("[Link]")
.newInstance();
[Link]("[Link]")
.newInstance();
[Link]("[Link]")
.newInstance();
//From version 10.15 new name. No need of initialization.
[Link]("[Link]")
.newInstance();
} catch (ClassNotFoundException | InstantiationException |
IllegalAccessException e) {
[Link]();
}
06.10.2025 JAT - Java Technologie 333
JDBC – Establishing Connection
• Using DriverManager
try {
Connection conn = [Link](
"jdbc:mysql://localhost/shop" +
"?user=shop&password=shop");
Statement stm = [Link]();
ResultSet rs = [Link]("show tables");
while([Link]()){
[Link]([Link](1));
}
} catch (SQLException e) {
[Link]();
}
06.10.2025 JAT - Java Technologie 334
JDBC – Connection string syntax
●
jdbc:oracle:thin:[USER/PASSWORD]@[HOST][:PORT]:SID
●
jdbc:derby:database_name[;create=true] //general for in memory DB
●
jdbc:derby://[host] [:port]/database_name[;create=true]
●
jdbc:mysql://[host][,failoverhost...][:port]/[database][?propertyName1]
[=propertyValue1][&propertyName2][=propertyValue2]…
●
jdbc:h2:[file:][<absolute_path>]<databaseName>
●
jdbc:h2:mem:<databaseName>
●
jdbc:postgresql://[host][:port]/<database_name>
06.10.2025 JAT - Java Technologie 335
JDBC – SQL Query
●
Creating and sending SQL query to database
Connection con = null;
Statement stmt = [Link](
ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = [Link](
"SELECT cof_name, price FROM coffes");
●
Other methods of class Statement
– boolean execute(String)
– ResultSet getResultSet()
– int executeUpdate(String) (for SQL INSERT, UPDATE, DELETE)
– close()
06.10.2025 Java 1 336
JDBC – Process Results
●
Read data and ResultSet metadata
ResultSetMetaData meta = [Link]();
while([Link]()){
for(int i=1; i<=[Link](); i++){
[Link]([Link](i) + ": "
+ [Link](i));
}
}
●
Moving cursor
– When result set is returned cursor point before first row
– next() return false if cursor move after last row
– last(), first() , previous() , relative(int) , absolute(int)
06.10.2025 Java 1 337
JDBC – Process Results II
●
Data reading
– getXXX() - byte, double, float, int, long, string, short, BigDecimal, Blob,
Date, Time
●
Meta-information
– ResultSetMetaData getMetaData()
06.10.2025 Java 1 338
JDBC – Update of Tables
●
Using SQL query (UPDATE myTable SET column1=‘value’ WHERE …)
●
Using ResultSet
Statement stmt = [Link](ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = [Link]("SELECT COF_NAME, PRICE FROM COFFEES");
[Link]();
[Link]("COF_NAME", "Foldgers");
[Link]();
●
cancelRowUpdates();
●
updateXXX() - double, float, int, string, Time, …
●
deleteRow()
●
moveToInsertRow()
06.10.2025 Java 1 339
JDBC – Automatically Generated Keys
●
Some database tables generate unique keys for all newly inserted records.
●
If application need know these keys it must use following lines of code:
[Link]("INSERT INTO autoincSample (column1) VALUES
('Record 1')", Statement.RETURN_GENERATED_KEYS);
ResultSet rs = [Link]();
●
Application have to pass flag RETURN_GENERATED_KEYS to method
executeUpdate
●
Application can obtain the keys using method getGeneratedKeys() and
returned result set contains all generated key from executed statement.
06.10.2025 Java 1 340
JDBC – Prepared Statements
●
Could be used if application repetitively process same statement only with
different data.
●
Usage of prepared statement preserve application against:
●
SQL injection attack
●
Bad data transformation to string (application side) and back to proper data
type (database side)
●
SQL statement is send to DBMS and compiled, after that can be processed
repetitively (time saving, better security)
PreparedStatement prepStm = [Link](
"UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
[Link](1, 75);
[Link](2, "Colombian");
[Link]();
06.10.2025 Java 1 341
JDBC – Transaction
●
Each single SQL statement is treated as transaction
●
Don’t exist command „BeginTransaction“ it is performed automatically
●
If application need more then one statement in one transaction, it have to
use method setAutoCommit()
[Link](false);
[Link]("UPDATE COFFEES SET SALES = 50 WHERE COF_NAME
LIKE ‘Colombia’");
[Link]("UPDATE COFFEES SET TOTAL = TOTAL + 50 WHERE
COF_NAME LIKE ‘Colombia’");
[Link]();
[Link](true);
06.10.2025 Java 1 342
JDBC – Transaction
●
rollback() – cancel transaction and change values in DB into state
before transaction begin.
●
SavePoint – allow rollback transaction to this point (SavePoint)
Savepoint svpt1 = [Link]("SAVEPOINT_1");
// Process some SQL statements
[Link](svpt1);
// Process some SQL statements
[Link]();
●
[Link](svpt1);
06.10.2025 Java 1 343
JDBC – Stored Procedures
●
Stored procedure creation
String createProcedure =
"proprietary code for a creating of a procedure";
Statement stmt = [Link]();
[Link](createProcedure);
●
Stored procedure call
CallableStatement cs = [Link](
"{call SHOW_SUPPLIERS(?, ?)}");
//[Link](int, String);
ResultSet rs = [Link]();
06.10.2025 Java 1 344
Processing Data with Java SE8 Streams
●
[Link]
[Link]
06.10.2025 Java 1 345
Processing Data with Java SE8 Streams
List<Transaction> groceryTransactions = new ArrayList<>();
for (Transaction t : groceryTransactions) {
if ([Link]() == [Link]) {
[Link](t);
}
}
[Link](groceryTransactions, new Comparator<>() {
public int compare(Transaction t1, Transaction t2) {
return [Link]().compareTo([Link]());
}
});
List<Integer> transactionsIds = new ArrayList<>();
for (Transaction t : groceryTransactions) {
[Link]([Link]());
}
List<Integer> transactionsIds = [Link]()
.filter(t -> [Link]() == [Link])
.sorted([Link](Transaction::getValue).reversed())
.map(Transaction::getId).toList();
06.10.2025 Java 1 346
Streams overview
List<Integer> transactionsIds = [Link]()
.filter(t -> [Link]() == [Link])
.sorted([Link](Transaction::getValue).reversed())
.map(Transaction::getId).toList();
06.10.2025 Java 1 347
Getting Started with Streams
●
Sequence of elements – to a sequenced set of values of a specific
element type but computed on demand;
●
Source - collections, arrays, or I/O resources;
●
Aggregate operations – functional operations – filter, map, reduce,
find, match, sorted
06.10.2025 Java 1 348
Stream operations - characteristics
●
Pipelining - Many stream
operations return a stream
themselves, it enables -
laziness and short-circuiting
●
Internal iteration
06.10.2025 Java 1 349
Streams Versus Collections
●
About a computation vs about data
●
Not replacement – collections allows multiple processing and
modification
●
For arguments, return values and instance variables collections are
preferred
[Link]().collect([Link]()); //Mutable list
[Link]().toList(); //Imutable list
06.10.2025 Java 1 350
Stream operations
●
Intermediate operations - together form pipeline – filter, sorted,
map
●
Terminal operations - reduce pipeline (close) – collect, reduce, min,
max, anyMatch, first…
06.10.2025 Java 1 351
Filtering
●
filter(Predicate)
●
distinct() - Returns a stream with unique elements (according to the
implementation of equals for a stream element)
●
limit(n)
●
skip(n)
Optional<Transaction> result = [Link]()
.filter(t -> [Link]() == [Link])
.findAny();
06.10.2025 Java 1 352
Optional<T>
●
It is a container class to represent the existence or absence of a
value.
●
Several methods
[Link]()
.filter(t -> [Link]() == [Link])
.findAny()
.ifPresent([Link]::println);
06.10.2025 Java 1 353
Mapping and reducing
List<String> words = [Link]("Oracle", "Java",
"Magazine");
List<Integer> wordLengths = [Link]()
.map(String::length)
.collect([Link]());
06.10.2025 Java 1 354
Numeric streams
●
IntStream - mapToInt
●
DoubleStream - mapToDouble
●
LongStreams – mapToLong
●
Additional methods: sum, average, summaryStatistics
int statementSum = [Link]()
.mapToInt(Transaction::getValue)
.sum(); // works!
06.10.2025 Java 1 355
range, rangeClosed
●
Another way for creation of numeric streams
●
Range – exclusive, rangeClosed – inclusive
IntStream oddNumbers = [Link](10, 30)
.filter(n -> n % 2 == 1);
06.10.2025 Java 1 356
Building streams
●
From collections – stream()
●
[Link]
Stream<Integer> numbersFromValues = [Link](1, 2, 3, 4);
●
[Link]()
IntStream numbersFromArray = [Link](new int [] {10,23,45});
●
[Link](), [Link]() – infinite streams
Stream<Integer> numbers = [Link](0, n -> n + 10);
●
Convert to a finite stream
[Link](5).forEach([Link]::println);
// 0, 10, 20, 30, 40
06.10.2025 Java 1 357
Parallel Stream
●
allows parallel processing
●
constructed as parallelStream()
●
Covered in “Programming in Java 2”
06.10.2025 Java 1 358
Date-Time in Java 8
●
Design principles
– Clear – well defined and their behavior is clear and expected
– Fluent – invocation should be chained
– Immutable
– Extensible
●
Packages
– [Link] – basic classes for calendar system defined in in ISO-8601
– [Link] – representing calendar other then default
– [Link] – formatting and parsing
– [Link]
– [Link]
06.10.2025 Java 1 359
Methods name convention
Prefix Method Type Use
of static factory Creates an instance where the factory is primarily validating the input parameters, not converting
them.
from static factory Converts the input parameters to an instance of the target class, which may involve losing
information from the input.
parse static factory Parses the input string to produce an instance of the target class.
format instance Uses the specified formatter to format the values in the temporal object to produce a string.
get instance Retuns a part of the state of the target object
is instance Queries the state of the target object.
with instance Returns a copy of the target object with one element changed; this is the immutable equivalent to a
set method on a JavaBean.
plus instance Retums a copy of the target object with an amount of time added.
minus instance Retums a copy of the target object with an amount of time subtracted.
to instance Converts this object to anothertype
at instance Combines this object with another.
06.10.2025 Java 1 360
Standard calendar - outline
●
DayOfWeek and MonthEnums
●
Date Classes
●
Date and Time Classes
●
Time Zone and Offset Classes
●
Instant Class
●
Parsing and Formatting
●
The Temporal Package
●
Period and Duration
●
Legacy Date-Time Code
●
06.10.2025 Java 1 361
DayOfWeek and Month Enums
●
DayOfWeek – enum with seven constants (MONDAY – SUNDAY)
DayOfWeek dow = [Link];
Locale lCS = [Link]("cs","CZ");
[Link]("%s%n", [Link](3));
[Link]([Link]([Link], lCS));
●
Month - enum with twelve constants (JANUARY - DECEMBER )
Month month = [Link];
[Link]("%d%n", [Link]());
[Link]([Link]([Link], lCS));
06.10.2025 Java 1 362
Date Classes
●
deal exclusively with date information, without respect to time or time zone
●
LocalDate – year-month-day in ISO calendar without TIME
LocalDate date = [Link](2000, [Link], 20);
LocalDate nextWed = [Link](
[Link]([Link]));
●
YearMonth
YearMonth date = [Link]();
[Link]("%s: %d%n", date, [Link]());
YearMonth date2 = [Link](2010, [Link]);
[Link]("%s: %d%n", date2, [Link]());
06.10.2025 Java 1 363
Date Classes II.
●
MonthDay
MonthDay date = [Link]([Link], 29);
boolean validLeapYear = [Link](2010);
●
Year
boolean validLeapYear = [Link](2012).isLeap();
06.10.2025 Java 1 364
Date and Time Classes
●
LocalTime
LocalTime lt = [Link]();
[Link]("%d, %d, %d %n",
[Link](), [Link](),[Link]());
●
LocalDateTime
[Link]("now: %s%n", [Link]());
[Link]("Apr 15, 1994 @ 11:30am: %s%n",
[Link](1994, [Link], 15, 11, 30));
[Link]("now (from Instant): %s%n",
[Link]([Link](), [Link]()));
[Link]("6 months from now: %s%n",
[Link]().plusMonths(6));
[Link]("6 months ago: %s%n",
[Link]().minusMonths(6));
06.10.2025 Java 1 365
Time Zone and Offset Classes
●
ZoneId
●
ZoneOffset
●
ZonedDateTime
●
OffsetDateTime
●
OffsetTime
06.10.2025 Java 1 366
Instant Class
●
nanoseconds from start of epoch (1.1.1970 )
●
methods isAfter, isBefore
Instant oneHourLater = [Link]().plus([Link](1));
long secondsFromEpoch = [Link](0L)
.until([Link](), [Link]);
LocalDateTime ldt = [Link](
timestamp, [Link]());
06.10.2025 Java 1 367
Parsing and Formatting
String input = "...";
try {
DateTimeFormatter formatter = [Link]("MMM d yyyy");
LocalDate date = [Link](input, formatter);
[Link]("%s%n", date);
} catch (DateTimeParseException exc) {/*...*/}
ZoneId leavingZone = /* ... */;
ZonedDateTime departure = /* ... */;
try {
DateTimeFormatter format = [Link](
"MMM d yyyy hh:mm a");
String out = [Link](format);
[Link]("LEAVING: %s (%s)%n", out, leavingZone);
} catch (DateTimeException exc) {/*...*/}
06.10.2025 Java 1 368
The Temporal Package – temporal adjuster
LocalDate date = [Link](2000, [Link], 15);
DayOfWeek dotw = [Link]();
[Link]("%s is on a %s%n", date, dotw);
[Link]("first day of Month: %s%n",
[Link]([Link]()));
[Link]("first Monday of Month: %s%n",
[Link]([Link]([Link])));
[Link]("last day of Month: %s%n",
[Link]([Link]()));
[Link]("first day of next Month: %s%n",
[Link]([Link]()));
[Link]("first day of next Year: %s%n",
[Link]([Link]()));
[Link]("first day of Year: %s%n",
[Link]([Link]()));
06.10.2025 Java 1 369
Duration and ChronoUnit
Instant t1, t2; Instant previous, current;
//... previous = null;
long ns = [Link](t1, long gap;
t2).toNanos(); current = [Link]();
Instant start = [Link](); if (previous != null) {
//... gap = [Link]
Duration gap = .between(previous, current);
[Link](10); }
Instant later =
[Link](gap);
06.10.2025 Java 1 370
Period
LocalDate today = [Link]();
LocalDate birthday = [Link](1960, [Link], 1);
Period p = [Link](birthday, today);
long p2 = [Link](birthday, today);
[Link]("You are " + [Link]() + " years, " +
[Link]() + " months, and " + [Link]()
+ " days old. (" + p2 + " days total)");
06.10.2025 Java 1 371
Legacy Date-Time Code
●
Classes:
– [Link]
– [Link]
●
Methods:
– [Link]() converts the Calendar object to an Instant.
– [Link]() converts a GregorianCalendar instance to a
ZonedDateTime.
– [Link](ZonedDateTime) creates a GregorianCalendar object
using the default locale from a ZonedDateTime instance.
– [Link](Instant) creates a Date object from an Instant.
– [Link]() converts a Date object to an Instant.
– [Link]() converts a TimeZone object to a ZoneId.
06.10.2025 Java 1 372
Legacy Date-Time Code II.
●
Mapping
– [Link] ↔ [Link]
– [Link] ↔ [Link]
– [Link] ↔ [Link] (ZoneOffset)
– [Link] (with date 1.1.1970) ↔ [Link]
– [Link] (with time 0:00) ↔ [Link]
06.10.2025 Java 1 373
6th lecture
06.10.2025 Java 1 374
XML – hystory
●
SGML (Standard Generalized Markup Language) is a standard for
defining generalized markup languages for documents. Which allows
define markup language as oven subsets. SGML is a complex
langugage which allows many markup syntaxes. That complexity is
disadvantage for common usage.
●
SGML is ISO standard called ISO 8879:1986 Information processing
—Text and office systems—Standard Generalized Markup Language
(SGML)
JAT - Java Technologie
06.10.2025 375
XML – historie
●
Language XML is created as profile (specialized subset) of SGML
and become very popular.
●
XML can be easy parsed and processed because of simplicity.
●
XHTML, GML, SVG, MathML, DocBook
06.10.2025 JAT - Java Technologie 376
XML – example
<math xmlns="[Link]
<mrow>
<msup>
<mfenced open="[" close="]">
<mrow>
<mi>a</mi>
[a+b]260
<mo>+</mo>
<mi>b</mi>
</mrow>
</mfenced>
<mn>260</mn>
</msup>
</mrow>
06.10.2025 JAT - Java Technologie 377
XML
●
XML document is modeled as tree (XML tree).
●
Notice: This data model was alsow presented in SGML language and
in database community is known as weakly structured data.
JAT - Java Technologie
06.10.2025 378
XML – well formed document
●
Element has type identified by name (known as tag). Exampel:
<book>...</book>.
●
Element can contains set of pairs attribute=’value’.
●
In text form XML document can be identified start (start-tag) and end
mark(end-tag) of element (<name>...</name>).
●
Text between start and end mark is called element content.
06.10.2025 Java 1 379
XML – well formed document
●
If element contains others tags and characters contents is called
mixed content. For example:
●
<a>Hi, <b>Mike</b></a>.
●
Elements with no content are called empty. Short syntax:
●
<img src="[Link]"/>.
●
First lien contains XML declaration, for example:
●
<?xml version="1.0" ?>
●
Document is called well formed if fullfil all these rules.
06.10.2025 Java 1 380
XML - tree
06.10.2025 Java 1 381
JavaAPI for XML
●
JAXP (SAX, DOM, XSLT, StAX)
– Apache Xerces
●
JAXB
– JavaEE
06.10.2025 Java 1 382
JavaAPI for XML – SAX
●
Event model
●
SAXParser inform about found
start or end tags, …
06.10.2025 Java 1 383
JavaAPI for XML – SAX
public class Parser {
public static void main(String[] args) throws SAXException, ParserConfigurationException
{
XMLReader xr = null;
try {
xr = [Link]().newSAXParser().getXMLReader();
} catch (SAXException e) {
[Link]();
}
MyHandler h = new MyHandler();
[Link](h);
[Link](h);
try {
InputSource source = new InputSource(new FileReader("[Link]"));
[Link](source);
} catch (Exception e) {
[Link]();
}
}
}
06.10.2025 Java 1 384
public class MyHandler extends DefaultHandler {
protected int counter = 0;
@Override
public void endDocument() throws SAXException {
[Link]("pocet: " + counter);
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
}
@Override
public void startDocument() throws SAXException {
}
@Override
public void startElement(String uri, String localName, String qName, Attributes
attributes) throws SAXException {
if ([Link]("dependency")) {
counter++;
}
}
}
06.10.2025 Java 1 385
JavaAPI for XML – DOM
●
Whole document is loaded to
memory and DOM tree is
created.
06.10.2025 Java 1 386
JavaAPI for XML – DOM
public class Tree {
public static void main(String[] args) {
DocumentBuilderFactory dbfactory = [Link]();
Document doc = null;
try {
DocumentBuilder builder = [Link]();
doc = [Link](new File("[Link]"));
} catch (Exception e) {
}
Element root = [Link]();
NodeList nl = [Link]();
for (int i = 0; i < [Link](); i++) {
String name = [Link](i).getNodeName();
[Link](name);
}
}
}
06.10.2025 Java 1 387
JavaAPI for XML – DOM XPath
try {
XPathFactory factory = [Link]();
XPath xPath = [Link]();
Object list = [Link]("project/dependencies/*", doc,
[Link]);
NodeList nl = (NodeList) list;
for (int i = 0; i < [Link](); i++) {
[Link]
.println([Link](i).getNodeName() + "='" +
[Link](i).getNodeValue() + "' :" + [Link](i).getTextContent());
}
} catch (XPathExpressionException e) {
[Link]();
}
06.10.2025 Java 1 388
JAXB – Java Architecture for XML binding
06.10.2025 Java 1 389
JAXB – save into XML
save XML document
[Link]
●
●
try {
File file = new File("[Link]");
JAXBContext jaxbContext = opens [Link] to
[Link]([Link]); [Link];
Marshaller jaxbMarshaller =
[Link](); ●
[Link]
// output pretty printed <dependency>
[Link]( <groupId>[Link]</groupId>
Marshaller.JAXB_FORMATTED_OUTPUT, true); <artifactId>[Link]-api</artifactId>
[Link]( <version>4.0.2</version>
Marshaller.MEDIA_TYPE, </dependency>
"application/json"); <dependency>
[Link](setting, file); <groupId>[Link]</groupId>
[Link](setting, <artifactId>jaxb-runtime</artifactId>
[Link]); <version>4.0.5</version>
} catch (JAXBException e) { </dependency>
[Link]();
}
06.10.2025 Java 1 390
JAXB
@XmlRootElement
public class GameSetting {
private String version;
private String saveFolder;
private List<Score> scores;
public GameSetting() {}
@XmlAttribute
public String getVersion() {
return version;
}
@XmlElement(name = "score")
@XmlElementWrapper(name = "player-scores")
public List<Score> getScores() {
return scores;
}
// ...
06.10.2025 Java 1 391
JAXB – load from XML
try {
File file = new File("[Link]");
JAXBContext jaxbContext = [Link](
[Link]);
Unmarshaller jaxbUnmarshaller = jaxbContext
.createUnmarshaller();
GameSetting setting2 = (GameSetting) jaxbUnmarshaller
.unmarshal(file);
[Link](setting2);
} catch (JAXBException e) {
[Link]();
}
06.10.2025 Java 1 392
JSON - The Object Model API
URL url = new URI("[Link]
try (InputStream is = [Link]()) {
●
[Link]
BufferedReader bufferedReader =
<!--
new BufferedReader(new InputStreamReader(is));
String content = [Link]()
[Link]
.collect([Link]("\n")); ct/[Link]/json -->
JSONObject apiResponse = new JSONObject(content); <dependency>
JSONArray results = [Link]("data"); <groupId>[Link]</groupId>
for (int i = 0; i < [Link](); i++) {
JSONObject user = [Link](i);
<artifactId>json</artifactId>
for (String propertyName : [Link]()) { <version>20240303</version>
[Link](propertyName + ": " </dependency>
+ [Link](propertyName));
}
[Link]("------------------------------");
}
}
06.10.2025 Java 1 393
JSON - The Object Model API
JSONObject jsonObject = new JSONObject();
[Link]("name", "David");
[Link]("score", 100);
// ...
GameSetting gameSetting = [Link]();
JSONObject result = new JSONObject(gameSetting);
[Link]([Link]());
06.10.2025 Java 1 394
JSON – JSONB API
The annotations used here are: ●
[Link]
●
@JsonbProperty – which is used for <dependency>
specifying a custom field name <groupId>[Link]</groupId>
<artifactId>[Link]-
●
@JsonbTransient – when we want to api</artifactId>
ignore the field during <version>3.0.1</version>
deserialization/serialization </dependency>
●
@JsonbDateFormat – when we want <dependency>
to define the display format of the date <groupId>[Link]</groupId>
●
@JsonbNumberFormat – for <artifactId>yasson</artifactId>
specifying the display format for <version>3.0.4</version>
numeric values </dependency>
●
@JsonbNillable – for enabling ●
[Link]
serialization of null values
● exports [Link];
06.10.2025 Java 1 395
JSONB
public class Score {
@JsonbProperty("nickname")
private String nick;
@JsonbNumberFormat(locale = "cs_CZ")
private float poins;
@JsonbDateFormat("[Link]")
private LocalDate when;
@JsonbTransient
private float averagePoints;
@JsonbNillable
private String customDescription;
public Score() {
}
06.10.2025 Java 1 396
JSONB
List<Score> scores = [Link](
Score::generate).limit(20).toList();
Jsonb jsonb = [Link]();
String result = [Link](scores);
[Link](result);
List<Score> readedScores = [Link](result,
new ArrayList<Score>() {}.getClass()
.getGenericSuperclass());
for (Score score : readedScores) {
[Link](score);
}
06.10.2025 Java 1 397
JSONB - configuration
JsonbConfig config = new JsonbConfig()
.withFormatting(true)
.withPropertyNamingStrategy(
PropertyNamingStrategy.LOWER_CASE_WITH_UNDERSCORES);
Jsonb jsonb = [Link](config);
06.10.2025 Java 1 398
Simple Networking
●
Java programs can use URLs to connect to and retrieve information
over the network. Uniform Resource Locator (URL) is an address of
a resource on the Internet (protocolID:resourceName).
●
Socket-based communication between programs. A socket is one
end of a two-way communication link between two programs running
on the network.
●
Communication based on datagrams. The delivery of datagrams is
not guaranteed nor is the order in which they are delivered.
●
06.10.2025 Java 1 399
Reading from URL
try {
URL urlKozusznik = new URI("[Link]
URLConnection conn = [Link]();
try (BufferedReader r = new BufferedReader(
new InputStreamReader([Link]()))) {
String line;
while (null != (line = [Link]())) {
[Link](line);
}
}
} catch (IOException e) {
[Link]();
}
06.10.2025 Java 1 400
The Socket Model
●
The server establishes a port number and waits. When the client requests
a connection, the server opens the socket connection with the accept()
method.
●
The client establishes a connection with host on a given port #.
●
Both client ans server communicate using InputStream and OutputStream.
Server Client
ServerSocket(port) Socket(host,port)
↓ //attempt to connect
accept()
OutputStream OutputStream
InputStream InputStream
06.10.2025 Java 1 401
Example: Simple Server
Intent - wait for client and send it a protected void listen() {
message when connected. try {
while (true) {
public class SimpleServer { Socket client = server
ServerSocket server; .accept();
String message = ObjectOutputStream out =
"Hello from server!"; New ObjectOutputStream(
[Link]());
public void run() { [Link](message);
try { [Link]();
server = new ServerSocket( [Link]();
7460, 5); }
listen(); } catch (Exception e) {
} catch (Exception e) { // ...
// ... }
} }
} }
06.10.2025 Java 1 402
Example: Simple Client
Intent - connect to the server and get a message.
public class SimpleClient {
public void run(String host) {
try (Socket server = new Socket(host, 7460)) {
ObjectInputStream input = new ObjectInputStream(
[Link]());
[Link]([Link]());
} catch (Exception e) {
[Link]("Error while getting message!");
}
}
}
06.10.2025 Java 1 403
Client/Server Application
public class ServerTest { public class ClientTest {
public static void main( public static void main(
String[] args) { String[] args) {
new SimpleServer().run(); new SimpleClient()
} .run([Link] > 0 ?
} args[0] : "localhost");
}
}
06.10.2025 Java 1 404
Thread of execution
●
“is the smallest sequence of programmed instructions that can be
managed independently by an operating system scheduler” -
Wikipedia for topic Thread(computing)
●
Multiple threads can exist in one process (running programs) and
they share resources (memory)
06.10.2025 Java 1 405
Threads
●
Represented by class Thread
●
Its method run() serves as a main routine for the thread.
●
Its method start() serves for starting thread operation/running.
●
A thread can be in state runnable, “not runnable” (sleep(), wait() or
blocking I/O) and dead (completion of the run() method).
●
A thread can have a priority from
●
Thread.MIN_PRIORITY (1) to Thread.MAX_PRIORITY (10).
06.10.2025 Java 1 406
[Link] – a multithreading friend
●
Define subclass (class MyThread1 e.g.) of the class Thread
●
Override method “run” – this code will be executed in new thread
●
Create new instance of your class (MyThread1) and call the method
“start”
●
thread end after leaving method “run”
06.10.2025 Java 1 407
Thread execution in an action
public class PrintThread extends public void run() {
Thread { Random random = new Random();
String name; //[Link](); vs.
[Link]();
[Link]().setName(name);
public PrintThread(String name) { for (int i = 0; i < 10 &&
[Link] = name; ![Link]().isInterrupted()
} ; i++) {
try {
[Link](random
public static void main( .nextLong(1000, 5000));
String[] args) { } catch (InterruptedException e) {
Thread t1 = new PrintThread("#1"); [Link]().interrupt();
Thread t2 = new PrintThread("#2"); }
[Link](); [Link](
[Link](); "Hello from " + name);
} }
} }
06.10.2025 Java 1 408
Interface Runnable - declares a run() method.
public class Print implements Runnable {
String name;
Print p1 = new Print ("#1",
int delay; (int) ([Link]()*2000));
public Print(String name, int delay) { Print p2 = new Print ("#2",
[Link] = name; (int) ([Link]()*2000));
[Link] = delay;
} // start() calls run in Print
public void run() {
new Thread(p1).start();
try { new Thread(p2).start();
[Link](delay);
} catch (InterruptedException e) {
}
[Link]("Hello from " +
name);
}
}
06.10.2025 Java 1 409
Method join
public class Producer implements Runnable { public class Consumer implements Runnable {
BlockingQueue<String> poolOfMessages; BlockingQueue<String> poolOfMessages;
public Producer(BlockingQueue<String> public Consumer(BlockingQueue<String>
poolOfMessages) { poolOfMessages) {
[Link] = poolOfMessages; [Link] = poolOfMessages;
} }
@Override @Override
public void run() { public void run() {
for (int i = 0; i < 10; i++) { try {
[Link]( for (int i = 0; i < 10; i++) {
i + " message from producer."); [Link](
try { [Link]());
[Link](200); }
} catch (InterruptedException e) } catch (InterruptedException e)
{/* ... */} {/* ... */}
} }}
}}
06.10.2025 Java 1 410
Method join
public static void main(String[] args)
throws InterruptedException {
BlockingQueue<String> queue = new LinkedBlockingDeque<String>();
Producer p = new Producer(queue);
Consumer c = new Consumer(queue);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]("Threads ended!!");
}
06.10.2025 Java 1 411
Method interrupt
●
Method of class Thread – signalization of interruption
●
In thread it is inspected whether interruption was signaled:
– static method [Link] – clear interrupted flags
– instance methods [Link] – doesn’t clear interrupted flag
– InterruptedException is thrown by blocking operations(sleep, wait) –
interrupted flag is cleared what exception is caught
06.10.2025 Java 1 412
Synchronization
●
Since Java is a multithreaded system, ●
The synchronized statement
care must be taken to prevent multiple attempts to acquire an exclusive
threads from modifying objects lock for the object or array and it
simultaneously. Section of code that does not execute the critical
must not be executed simultaneously section code until it can obtain this
are known as “critical section”. lock.
●
Statement synchronized:
●
Method modifier synchronized
synchronized (expression) {
indicates that entire method is
//block or it can be simple
critical section code. For a
statement synchronized instance method,
} Java obtains an exclusive lock on
the instance. For a synchronized
●
expression must resolve to an object class method, Java obtains an
●
block is the code of critical section. exclusive lock on the class.
●
06.10.2025 Java 1 413
Monitor
●
A monitor is associated with a specific public class Reentrant {
object (or array) and functions as a lock public synchronized void a() {
on that object. When a thread holds the b();
monitor for some object, other threads [Link](
are locked out and cannot inspect or "here I am, in a()");
modify this object. }
●
The Java runtime system allows a thread
to re-acquire a monitor that it already public synchronized void b() {
holds because Java monitors are [Link](
reentrant. Reentrant monitors are "here I am, in b()");
important because they eliminate the }
possibility of a single thread deadlocking }
itself on a monitor that it already holds.
06.10.2025 Java 1 414
Multiple-Thread Communication
●
Method wait() of the Object class makes a thread wait until some
condition occurs.
●
Method notify() of the Object class tells a waiting thread that a
condition occured.
●
06.10.2025 Java 1 415
Example: Producer/Consumer
●
Intent - the Producer generates an integer between 0 and 9, stores it
in a Pool object, and prints the generated number. To make the
synchronization problem more interesting, the Producer sleeps for a
random amount of time between 0 and 1000 milliseconds before
repeating the number generating cycle. The Consumer consumes
all integers from the Pool (the exact same object into which the
Producer put the integers in the first place) as quickly as they
become available.
06.10.2025 Java 1 416
Producer
public class Producer extends Thread {
private Pool pool;
public Producer(Pool pool) {
[Link] = pool;
}
public void run() {
for (int i = 0; i < 10; i++) {
// Wait until the previous value is consumed
[Link](i);
[Link]("Producer put: " + i);
try {
[Link]((int) ([Link]() * 1000));
} catch (InterruptedException e) {
}
}
}
}
06.10.2025 Java 1 417
Consumer
public class Consumer extends Thread {
private Pool pool;
public Consumer(Pool pool) {
[Link] = pool;
}
public void run() {
int value;
for (int i = 0; i < 10; i++) {
// Wait until the value is produced
value = [Link]();
[Link]("Consumer got: " + value);
}
}
}
06.10.2025 Java 1 418
Shared Pool
public class Pool { public void put(int i) {
private volatile int contents; synchronized (this) {
private volatile boolean while (isFull) {
isFull = false; try {
public synchronized int get() {
[Link]();
while (!isFull) {
try { } catch
wait(); (InterruptedException e)
} catch {/*...*/}
(InterruptedException e) }
{/*...*/} contents = i;
} isFull = true;
int value = contents; [Link]();
isFull = false;
}
notifyAll();
return value; }
} }
06.10.2025 Java 1 419
Producer/Consumer Test
public class ProducerConsumerTest {
public static void main(String[] args) {
Pool pool = new Pool();
Producer p = new Producer(pool);
Consumer c = new Consumer(pool);
[Link]();
[Link]();
}
}
06.10.2025 Java 1 420
High level concurrency API - executor
●
Interfaces:
– Executor
– ExecutorService
– ScheduledExecutorService
●
instantied with static methods in class Executors
06.10.2025 Java 1 421
High level concurrency API - Future
●
interface for cancelable tasks
●
implementations:
– FutureTask – implements also Runnable,
– CompletableFuture – more advance, supports chaining of tasks,
●
instantied with static methods supplyAsync, runAsync – can be passed Executor
06.10.2025 Java 1 422
06.10.2025 Java 1 423
06.10.2025 Java 1 424
06.10.2025 Java 1 425