J02-JavaBasics
J02-JavaBasics
Version 2.3.3
© Maurizio Morisio, Marco Torchiano, 2024
Comments
§ C-style comments (multi-lines)
/* this comment is so long
that it needs two lines */
4
Code blocks and Scope
§ Java code blocks are the same as in C
§ Each block is enclosed by braces { }
and starts a new scope for the variables
§ Variables can be declared both at the
beginning and in the middle of a block
5
Control statements
§ Similar to C
¨ if-else
¨ switch,
¨ while
¨ do-while
¨ for
¨ break
¨ continue
6
Switch statements with strings
§ Strings can be used as cases values
switch(season){
case "summer":
case "spring": temp = "hot";
break;
}
- Compiler generates more efficient bytecode
from switch using String objects than from
chained if-then-else statements.
Boolean
§ Java has an explicit type (boolean) to
represent logical values (true, false)
§ Conditional constructs require
boolean conditions
¨ Illegal to evaluate integer condition
int x = 7; if(x){…} //NO
¨ Use relational operators if (x != 0)
9
Elements in an OO program
Structural elements
(types) § Class
(compile time) § Primitive type
10
Classes and primitive types
Type
§ Class § type primitive
class Exam {} int, char,
float
Instance
§ Variable of type § Variable of type
reference primitive
Exam e; int i;
e = new Exam();
11
PRIMITIVE TYPES
Primitive type
§ Defined in the language:
¨ int, double, boolean, etc.
§ Instance declaration: int i;
¨ Declares instance name 0
13
Primitive types Logical
size !=
Type Size Encoding memory
occupation
boolean 1 bit -
char 16 bits Unicode UTF16
byte 8 bits Signed integer 2C
short 16 bits Signed integer 2C
int 32 bits Signed integer 2C
long 64 bits Signed integer 2C
float 32 bits IEEE 754 sp
double 64 bits IEEE 754 dp
void -
14
Literals
§ Literals of type int, float, char, strings
follow C syntax
¨ 123 256789L 0xff34 123.75
0.12375e+3
¨ ’a’ ’%’ ’\n’ "prova" "prova\n"
§ Boolean literals (do not exist in C) are
¨ true, false
15
Operators (integer and f.p.)
§ Operators follow C syntax:
¨ arithmetical + - * / %
¨ relational == != > < >= <=
¨ bitwise (int) & | ^ << >> ~
¨ Assignment = += -= *= /=
%= &= |= ^=
¨ Increment ++ --
§ Chars are considered like integers
(e.g. switch)
16
Logical operators
§ Logical operators follows C syntax:
&& || ! ^
§ Warning: logical operators work ONLY
on boolean operands
¨ Type int is NOT treated like a boolean:
this is different from C
¨ Relational operators return boolean
values
17
CLASSES AND OBJECTS
Class
§ Defined by developer (e.g., Exam) or in the Java
runtime libraries (e.g., String)
§ The declaration
Exam e; e null
Object
e = new Exam(); e 0Xffe1 Exam
19
Class
§ Object descriptor
¨ Defines the common structure of a set of
objects
§ Consists of a set of members
¨ Attributes
¨ Methods
¨ Constructors
Class - definition
public class Car {
String color; Name
String brand; Car
boolean turnedOn; Attributes
color
void turnOn() { brand
turnedOn = true; turnedOn
Methods
}
turnOn
void paint (String newCol) { paint
color = newCol; printState
}
void printState () {
System.out.println(“Car “ + brand + “ “ + color);
System.out.println(“the engine is”
+(turnedOn?”on”:”off”));
}
}
21
Attributes
§ Attributes describe the data that can
be stored within objects
§ They are like variables, defined by:
¨ Type
¨ Name
23
Objects
§ An object is identified by:
¨ Class, which defines its structure (in
terms of attributes and methods)
¨ State (values of attributes)
¨ Internal unique identifier
§ An object can be accessed through a
reference
¨ Any
object can be pointed to by one or
more references
- Aliasing
24
Objects and references
Car a1, a2;
a1 = new Car();
a1.paint("yellow");
a2 = a1;
a1 = null;
a2 = null;
a1 ?
a2 ?
Two uninitialized references
are created, they can’t be
used in any way.
A reference is not an object
26
Objects and references
Car a1, a2;
a1 = new Car();
a1.paint("yellow");
a2 = a1;
a1 = null;
a2 = null; a1 : Car
a1 ?
a2 ? An object is created
and the “pointer”
stored into the
reference a1
27
Objects and references
Car a1, a2;
a1 = new Car();
a1.paint("yellow");
a2 = a1;
a1 = null;
a2 = null; a1 : Car
w ”)
ye llo
a1 ? nt (“
p ai
a2 ? Method paint() is
invoked on the
object through the
reference a1
28
Objects and references
Car a1, a2;
a1 = new Car();
a1.paint("yellow");
a2 = a1;
a1 = null;
a2 = null; a1 : Car
a1
a2 ?
Two references point
to the same object.
This is aliasing
29
Objects and references
Car a1, a2;
a1 = new Car();
a1.paint("yellow");
a2 = a1;
a1 = null;
a2 = null; a1 : Car
a1 null X
a2
Only one reference
points to the object
30
Objects and references
Car a1, a2;
a1 = new Car();
a1.paint("yellow");
a2 = a1;
a1 = null;
a2 = null; a1 : Car
a1 null
32
The keyword new
§ Creates a new instance of the specific class
§ Allocates the required memory in the heap
§ Calls the constructor of the object
¨ a special method without return type and named
like the class
§ Returns a reference to the new object
§ Constructor may have parameters, e.g.
¨ String s = new String("ABC");
33
Heap
§ A part of the memory used by an executing
program to store data dynamically created
at run-time
§ Java: new
¨ Instances (Objects) are always in the heap
34
Constructor (1)
§ Constructor is a special method containing
the operations (e.g. initialization of
attributes) to be executed on each object as
soon as it is created
§ Attributes are always initialized
§ If no constructor at all is declared, a default
one (with no arguments) is provided
§ Overloading of constructors is often used
35
Constructor (2)
§ Attributes are always initialized before
any possible constructor
¨ Attributes are initialized with default values
- Numeric: 0 (zero)
- Boolean: false
- Reference: null
§ Return type must not be declared for
constructors
¨ Ifpresent, constructor is considered a
method and it is not invoked upon
instantiation
Current object – a.k.a this
§ During the execution of a method it is
possible to refer to the current object
using the keyword this
¨ Theobject upon which the method has
been invoked
§ This makes no sense within methods
that have not been invoked on an
object
¨ E.g. the main method
Method invocation
§ A method is invoked using dotted
notation
objectReference.method(parameters)
§ Example:
38
Note
§ If a method is invoked from within
another method of the same object
dotted notation is not mandatory
class Book {
int pages;
void readPage(int n) { … }
void readAll() {
for(int i=0; i<pages; i++){
readPage(i);
}
}
}
39
Note (cont’d)
§ In such cases this is implied
§ It is not mandatory
class Book {
int pages;
void readPage(int n){…}
void readAll() {
for(…){ equivalent
readPage(i);
} }
} void readAll() {
for(…){
this.readPage(i);
} }
40
Access to attributes
§ Dotted notation
objectReference.attribute
¨ A reference is used like a normal variable
41
Access to attributes
§ Methods accessing attributes of the
same object do not need to use the
object reference
class Car {
String color;
…
void paint(){
color = “green”;
// color refers to current obj
}
}
42
Using “this” for attributes
§ The use of this is not mandatory
§ It can be useful in methods to
disambiguate object attributes from
local variables
class Car{
String color;
...
void paint (String color) {
this.color = color;
}
}
43
Chaining dotted notations
§ Dotted notations can be combined in a
single expression
System.out.println(“Hello world!”);
44
Method Chaining
public class Counter {
private int value;
public Counter reset(){
value=0; return this;
}
public Counter increment(int by){
this.value+=by; return this;
}
public Counter print(){
System.out.println(value);
return this;
} Counter cnt = new Counter();
} cnt.reset().print()
.increment(10).print()
.decrement(7).print();
Operations on references
§ Only the comparison operators == and !=
are defined
¨ Note well: the equality condition is evaluated on
the values of the references and NOT on the
objects themselves!
¨ The relational operators tells whether the
references points to the same object in memory
§ Dotted notation is applicable to object
references
§ There is NO pointer arithmetic
46
Overloading
§ Several methods in a class can share
the same name
§ They must have have distinct
signature
§ A signature consists of:
¨ Method name
¨ Ordered list of argument types
Overloading: disambiguation
§ Invocation of an overloaded method is
potentially ambiguous
§ Disambiguation is performed by the
compiler based on actual parameters
¨ The method definition whose argument
types list matches the actual parameters,
is selected
Overloading
class Car {
String color;
void paint(){
color = "white";
}
void paint(int i){ … }
void paint(String newCol){
color = newCol;
}
}
Constructors with overloading
class Car { // …
// Default constructor, creates a red Ferrari
public Car(){
color = "red";
brand = "Ferrari";
}
// Constructor accepting the brand only
public Car(String carBrand){
color = "white”;
brand = carBrand;
}
// Constructor accepting the brand and the color
public Car(String carBrand, String carColor){
color = carColor;
brand = carBrand;
}
}
51
Destruction of objects
§ Memory release, in Java, is no longer a
programmer’s concern
¨ Managed memory language
§ Before the object is really destroyed
the method finalize, if defined, is
invoked:
public void finalize()
52
SCOPE AND ENCAPSULATION
Scope and Syntax
§ Visibility modifiers
¨ Applicable to members of a class
§ private
¨ Member is visible and accessible from
instances of the same class only
§ public
¨ Member is visible and accessible from
everywhere
54
Info hiding
class Car {
public String color;
Car a = new Car();
}
a.color="white"; // ok
class Car {
private String color;
public void paint(String color)
{this.color = color;}
better }
Car a = new Car();
a.color = "white"; // error
a.paint("green"); // ok
55
Info hiding
class Car{
private String color;
public void paint(); no
}
class B {
public void f1(){
yes ...
};
}
56
Access
Private
(attribute / yes no
method)
Public
(attribute / yes yes
method)
57
Getters and setters
§ Methods used to read/write a private
attribute
§ Allow to better control in a single
point each write access to a private
field
public String getColor() {
return color;
}
public void setColor(String newColor) {
color = newColor;
}
58
Example without getter/setter
public class Student {
public String first;
public String last;
public int id;
public Student(…){…}
}
59
Example without getter/setter
class StudentExample {
public static void main(String[] args) {
// defines a student and her exams
// lists all student’s exams
Student s=new Student(“Alice",“Green",1234);
Exam e = new Exam(30);
e.student = s;
// print vote
System.out.println(e.grade);
// print student
System.out.println(e.student.last);
}
}
60
Example with getter/setter
class StudentExample {
public static void main(String[] args) {
Student s = new Student(“Alice”, “Green”,
1234);
Exam e = new Exam(30);
e.setStudent(s);
// prints its values and asks students to
// print their data
e.print();
}
}
61
Example with getter/setter
public class Student {
private String first;
private String last;
private int id;
public String toString() {
return first + " " +
last + " " +
id;
}
}
62
Example with getter/setter
public class Exam {
private int grade;
private Student student;
public void print() {
System.out.println(“Student ” +
student.toString() + “got ” + grade);
}
public void setStudent(Student s) {
this.student =s;
}
}
63
Getters & setters vs. public fields
§ Getter
¨ Allowchanging the internal
representation without affecting
- E.g. can perform type conversion
§ Setter
¨ Allow
performing checks before
modifying the attribute
- E.g. Validity of values, authorization
Modifier / Query methods
§ Modifiers
¨ Change the state of the object but do not
return a value
- e.g. setters
§ Query
¨ Return a result and do not change the
state of the object
¨ No side-effects
- e.g. getters
Modifier / Query Separation
§ Invocations to
¨ queries can be added, removed, and
swapped without affecting the overall
behavior
¨ modifiers cannot be touched without
affecting the behavior
§ Important to clearly separate them:
¨ Queries return a value
¨ Modifiers return void
See: https://www.martinfowler.com/bliki/CommandQuerySeparation.html
Original concepts in: B.Meyer, Object-Oriented Software Construction, Prentice-Hall, 1997
Package
§ Class is a better mechanism of
modularization than a procedure
§ But it is still small, when compared to
the size of an application
§ For the purpose of code organization
and structuring Java provides the
package feature
67
Package
§ A package is a logic set of class
definitions
§ These classes consist in several files, all
stored in the same folder
§ Each package defines a new scope (i.e.,
it puts bounds to visibility of names)
§ It is therefore possible to use same class
names in different package without
name-conflicts
68
Package name
§ A package is identified by a name with
a hierarchic structure (fully qualified
name)
¨ E.g. java.lang (String, System, …)
69
Examples
§ java.awt
¨ Window
¨ Button
¨ Menu
§ java.awt.event (sub-package)
¨ MouseEvent
¨ KeyEvent
70
Creation and usage
§ Declaration:
¨ Package statement at the beginning of
each class file
package packageName;
§ Usage:
¨ Import statement at the beginning of
class file (where needed) Import single class
(class name is in
import packageName.className; scope)
71
Access to a class in a package
§ Referring to a method/class of a package
int i = myPackage.Console.readInt()
72
Default package
§ When no package is specified, the
class belongs to the default package
¨ The default package has no name
§ Classes in the default package cannot
be accessed by classes residing in
other packages
§ Usage of default package is a bad
practice and is discouraged
Package and scope
§ Scope rules also apply to packages
§ The “interface” of a package is the set of
public classes contained in the package
§ Hints
¨ Consider a package as an entity of
modularization
¨ Minimizethe number of classes, attributes,
methods visible outside the package
Package visibility
Package P
class A {
public int a1; class B {
75
Visibility w/ multiple packages
§ public class A { }
¨ Class
and public members of A are visible
from outside the package
§ class B { } Package visibility
¨ Class and any members of B are not
visible from outside the package
§ private class A { }
¨ Illegal: why?
The class and its members would
be visible to themselves only
76
Multiple packages
Package P
class A { class B {
public int a1; public int a3;
private int a2; private int a4;
public void f1(){} }
}
no no
Package Q
class C {
public void f2(){}
}
77
Multiple packages
Package P
yes no
Package Q
class C {
public void f2(){}
}
78
Access rules
Method of other Method of other
Method of the
class in the same class in other
same class
package package
Public member in
public class
Yes Yes Yes
79
WRAPPER CLASSES
String
§ No primitive type to represent string
§ String literal is a quoted text
§C
¨ char s[] = “literal”
¨ Equivalence between strings and char
arrays
§ Java
¨ char[] != String
¨ String class in java.lang package
82
Wrapper Classes
Defined in java.lang package
Primitive type Wrapper Class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
void Void
83
Conversions
wi.intValue()
Integer wi
wi.toString()
Integer.valueOf(s)
new Integer(s)
new Integer(i)
Integer.valueof(i)
int i String s
Integer.parseInt(s)
String.valueOf(i)
""+i
84
Example
Integer obj = new Integer(88);
String s = obj.toString();
int i = obj.intValue();
int j = Integer.parseInt("99");
int k=(new Integer(99)).intValue();
85
Using Scanner
§ Scanner can be initialized with a string
Scanner s = new Scanner("123");
§ then values can be parsed
int i = s.nextInt();
§ In addition a scanner is able to parse
several numbers in the same string
Autoboxing
§ Since Java 5, the conversion between
primitive types and wrapper classes is
performed automatically (autoboxing)
Integer i= new Integer(2); int j;
j = i + 5;
//instead of:
j = i.intValue()+5;
i = j + 2;
//instead of:
i = new Integer(j+2);
87
Character
§ Utility methods on the kind of char
¨ isLetter(),isDigit(),
isSpaceChar()
§ Utility methods for conversions
¨ toUpper(), toLower()
88
ARRAYS
Array
§ An array is an ordered sequence of
variables of the same type which are
accessed through an index
§ Can contain both primitive types or
object references (but no object
values)
§ Array dimension can be defined at
run-time, during object creation
(cannot change afterwards)
90
Array declaration
§ An array reference can be declared
with one of these equivalent syntaxes
int[] a;
int a[];
§ In Java an array is an Object and it is
stored in the heap
§ Array declaration allocates memory
space for a reference, whose default
value is null
a null
91
Array creation
§ Using the new operator…
int[] a;
a = new int[10];
String[] s = new String[5];
92
Example - primitive types
a heap
int[] a; null
a heap
a = new int[6]; 0
0
0
0
0
0
primes heap
int[] primes = 2
3
{2,3,5,7,11,13}; 5
7
11
13
93
Example - object references
s heap
String[] s = new null
String[6]; null
null
null
null
null
s heap
s[1] = new null
String(“abcd”); null “abcd”
null
null
null
Person[] p =
heap
{new Person(“John”) , p
94
Operations on arrays
§ Elements are selected with brackets [ ]
(C-like)
¨ But Java makes bounds checking
95
Operations on arrays
§ An array reference is not a pointer to
the first element of the array
§ It is a pointer to the array object
96
For each
§ New loop construct:
for( Type var : set_expression )
¨ Very compact notation
¨ set_expression can be
- either an array
- a class implementing Iterable
¨ The compiler can generate automatically
the loop with correct indexes
- Less error prone
97
For each - example
§ Example:
for(String arg : args){
//...
}
¨ is equivalent to
for(int i=0; i<args.length;++i){
String arg= args[i];
//...
}
98
Multidimensional array
§ Implemented as array of arrays
heap table[0][2]
table
null
null null
null “Mary”
null
table[0]
99
Rows and columns
§ Since rows are not stored in adjacent
positions in memory they can be
easily exchanged
100
Rows with different length
§ A matrix (bidimensional array) is
indeed an array of arrays
int[][] triangle = new int[3][]
triangle
null
null
null
heap
101
STATIC ATTRIBUTES AND METHODS
Static attributes
§ Represent properties which are common to
all instances of a class
¨ A single copy of a static attribute is shared by
all instances of the class
¨ Sometimes called class attributes as opposed to
instance attributes
¨ Static attributes exists before any object is
created
¨ A change performed by any object is visible to
all instances at once
§ They are defined with the static modifier
105
Static attributes: why
§ Used to keep a shared property
¨A count of created instances
¨ A pool of all instances
§ valueOf(String)
¨ Returns the integer corresponding to the
parsed string
¨ Same as:
new Integer(Integer.parseInt(s))
Final Attributes
§ An attribute declared as final:
¨ cannot be changed after object construction
¨ can be initialized inline or by the constructor
class Student {
final int years=3;
final String id;
public Student(String id){
this.id = id;
}
}
Final variables / parameters
§ Final parameters cannot be changed
¨ Non final parameters are treated as local
variables (initialized by the caller)
§ Final variables
¨ Cannot be modified after initialization
¨ Initialization can occur at declaration or
later
Constants
§ Use final static modifiers
¨ final implies not modifiable
¨ static implies non redundant
final static float PI = 3.14;
…
PI = 16.0; // ERROR, no changes
final static int SIZE; // missing init
119
Static initialization block
§ Block of code preceded by static
§ Executed at class loading time
Factory method
+getInstance(): Singleton
singletonOperation()
private Singleton() { }
private static Singleton instance;
public static Singleton getInstance(){
if(instance==null)
instance = new Singleton();
return instance;
}
124
Fluent Interfaces
§ Method to design OO API based on
extensive use of method chaining
§ The goal is to improve readability
¨ Code looks like prose
¨ Often used to build complex objects
See: https://www.martinfowler.com/bliki/FluentInterface.html
P [W] = ⋅ V[V]
T[h]
Example ⎯⎯⎯⎯ ⎯⎯⎯⎯
u(P ) = P ∗ (u(C)/C + u(T)/T + u
131
Variable arguments- example
static int min(int... values){
int res = Integer.MAX_VALUE;
for(int v : values){
if(v < res) res=v;
}
return res;
}
public static void main(String[] args) {
int m = min(9,3,5,7,2,8);
System.out.println("min=” + m);
}
132
Enum
§ Defines an enumerative type
public enum Suits {
SPADES, HEARTS, DIAMONDS, CLUBS
}
§ Variables of enum types can assume
only one of the enumerated values
Suits card = Suits.HEARTS;
¨ They allow much stricter static checking
compared to integer constants (e.g. in C)
Enum
§ Enum can are similar to a class that
automatically instantiates the values
class Suits {
public static final Suits HEARTS=
new Suits (“HEARTS”,0);
public static final Suits DIAMONDS=
new Suits(“DIAMONDS”,1);
public static final Suits CLUBS=
new Suits (“CLUBS”, 2);
public static final Suits SPADES=
new Suits (“SPADES”, 3);
private Suits (String enumName, int index)
{…}
}
134
NESTED CLASSES
Nested class types
§ Static nested class
¨ Within the container name space
§ Inner class
¨ As above + contains a link to the creator
container object
§ Local inner class
¨ As above + may access (final) local variables
§ Anonymous inner class
¨ As above + no explicit name
(Static) Nested class
§ A class declared inside another class
package pkg;
class Outer {
static class Nested {
}
}
§ Similar to regular classes
¨ Subject to usual member visibility rules
¨ Fully qualified name includes the outer
class:
- pkg.Outer.Inner
(Static) Nested class - Usage
§ Static nested classes can be used to
hide classes that are used only within
another class
¨ Reduce namespace pollution
¨ Encapsulate internal details
¨ Nested class lies within the scope of the
outer class
(Static) Nested class - Example
public class StackOfInt{
private static class Element {
int value;
Element next;
}
private Element head
public void push(int v){ … }
public int void pop(){ … }
}
Inner Class
§ Linked to an instance
¨ A.k.a.
non-static nested class
package pkg;
class Outer {
class Inner{
}
}
X x = new X();
System.out.println(x.plus());
}
¨ References to local variables are allowed
- Replaced with “current” value
- Set of such local variables is called closure
Local Inner Class
§ Declared inside a method
public void m(){
int j=1;
class X { 1
int plus(){ return j + 1; }
} What result should
j++; we expect?
X x = new X();
System.out.println(x.plus());
}
¨ Local
variable cannot be changed after
being referred to by an inner class
Local Inner Class
§ Declared inside a method
public void m(){
final int j=1;
class X {
int plus(){ return j + 1; }
}
j++;
X x = new X();
System.out.println(x.plus());
}
¨ Local
variables used in local inner classes
should be declared final
- Or be effectively final
Anonymous Inner Class
§ Local class without a name
§ Only possible with inheritance
¨ Implement an interface, or
¨ Extend a class
§ See: inheritance
MEMORY MANAGEMENT
Memory types
Depending on the kind of elements they
include:
§ Static memory
¨ elements living for all the execution of a
program (class definitions, static variables)
§ Heap (dynamic memory)
¨ elements created at run-time (with ‘new’)
§ Stack
¨ elements created in a code block (local
variables and method parameters)
148
Memory types
Memoria est omnis divisa in partes tres...
static
dynamic
(heap)
local
(stack)
Example
151
Garbage collector
§ Component of the JVM that cleans the
heap memory from ‘dead’ objects
§ Periodically it analyzes references and
objects in memory
§ ...and then it releases the memory for
objects with no active references
§ No predefined timing
¨ System.gc() can be used to suggest GC
to run as soon as possible
152
Object destruction
§ It’s not made explicitly but it is made
by the JVM garbage collector when
releasing the object’s memory
¨ Method finalize() is invoked upon
release
§ Warning: there is no guarantee an
object will be ever explicitly released
153
Finalization and garbage collection
class Item {
public void finalize(){
System.out.println("Finalizing”);
}
}
155