Chapter2 (Full)
Chapter2 (Full)
Introduction to Java
1
What is Java?
• Java is a high-level, object-oriented, platform-independent
programming language.
• Developed by Sun Microsystems in 1995 (now owned by
Oracle).
• Designed with the principle of "Write Once, Run Anywhere"
(WORA).
2
Plan
• Operators
• Control Statements
• Variables in Java
• Primitive Types in Java
• Object Types in Java
API Classes
User-Defined Classes
Arrays
• Strings with the String Class
• Package
3
Arithmetic and Relational Operators
• Arithmetic and relational operators in Java are the same as in
the C language, with some differences in behaviour.
• Arithmetic Operators:
The arithmetic operators are: +, -, *, /, %, ++, --.
A key difference is that the + operator can also be used to
concatenate strings.
• Relational Operators:
The relational operators are: <, <=, >, >=, ==, !=.
The == and != operators can also be applied to objects.
4
Example
• Consider the following code snippet:
int i = 10;
int n = i++%5;
• What are the values of i and n after executing the code?
• What would be the final values of i and n if the postfix
increment operator (i++) was replaced with the prefix
increment operator (++i)?
5
Logical Operators
• The logical operators in Java are:
Operator Meaning
! Negation
& Logical AND
^ Exclusive OR
| Inclusive OR
&& Short-circuit AND
|| Short-circuit OR
6
Short-Circuit Operators (&& and ||)
• Both & and && represent logical AND, just
as | and || represent logical OR.
• However, the short-circuit operators (&& and ||) have an
interesting property: the second operand (the one on the right
side of the operator) is only evaluated if its value is necessary
to determine the truth value of the expression
• Example : a<b && c<d
• In this expression, a < b is evaluated first. If the result is false,
there is no need to evaluate c < d because the entire expression
will be false regardless.
7
Control Statements in Java
• Control statements in Java are similar to those in C. They
allow for:
• Decision-making: if...else and switch statements.
• Looping: do...while, while, and for loops.
• Additionally, there is a useful loop syntax called the for-each
loop, which is particularly suited for arrays, strings, and other
collections. We will explore this later.
8
Variables in Java
• A variable is a named memory location that stores data of
a specific type.
• In Java, variables must be declared before they can be
used.
• Naming Conventions:
Variable names must start with a letter, $, or _ (underscore).
They cannot start with a digit.
Variable names are case-sensitive (e.g., age and Age are
different).
Variable names should be meaningful and follow camelCase
(e.g., studentName, totalScore) except for constants (we will
revisit this later).
9
Scope of variables
• The scope of a variable determines where it can be accessed in
the program.
• Variables can have:
• Local Scope: Declared inside a method or block. They are
accessible only within that method or block.
• Instance Scope: Declared inside a class but outside any
method. They belong to an instance of the class.
• Class Scope (Static): Declared with the static keyword. They
belong to the class itself, not to any specific instance.
10
Final variables (constants)
• In Java, the keyword final before a variable declaration means that
the value of the variable cannot be changed during execution.
• final does not declare symbolic constants as in C; it simply ensures
that the value of a variable does not change after it is initialized.
• By convention, constant variable names are written in UPPERCASE
with underscores separating words (e.g., MAX_VALUE).
• Example:
final int n = 20; // n is initialized only once
final int NUMBER = 20; // Declaration of a constant
11
Examples Expression 1 : n will
be initialised once
only
Expression 1 :
final int n = 20;
Expression 2 :
Expression 2 is
final int n;
correct even if n has
... not got a value yet
n = 5 * 4 ;
Expression 3 :
final int NOMBRE = 20; Expression 3:
declaration of a
constant
12
Variables types
• In Java, according to the type used to declare a variable, we
distinguish :
• Primitive Variables: Store values of primitive data types.
• Reference Variables: Store references to objects.
13
Types in Java
• Java is a statically typed language, meaning that all variables must
be declared before they can be used. This involves specifying the type
and name of the variable.
• Java distinguishes two main categories of types :
• Primitive Data Types (e.g., int, double, boolean).
• Object Types :
API classes (e.g., System, String,..)
User-defined classes
Arrays
14
Primitive Types in Java
• Java has a number of basic types called primitive types,
which are used to manipulate integers, floating-point
numbers, characters, and booleans.
• Java defines the exact characteristics of primitive types,
including:
Memory size
Associated arithmetic behaviour
• As a result, regardless of the machine, a float value will have
the same size, limits, and precision.
• Java is the first language to ensure that the same program,
executed in different environments, will produce the same
results.
15
Integer Types
• Java has four integer types, each corresponding to different memory
sizes and limits:
Type Size (bytes) min max
byte 1 -128 127
short 2 -32768 32767
int 4 Integer.MIN_VALUE Integer.MAX_VALUE
• Integer Constants:
By default, an integer constant is of type int.
To force an integer constant to be of type long, append l or L to the
number (e.g., 23L).
16
Floating-Point Types
• Java provides two floating-point types, each corresponding to
different memory sizes: float and double.
• Floating-point constants are of type double by default.
• To force a double to be treated as a float, append F or f to the
number.
• Example:
float x ;
x = 12.5f ;
17
The char Type
• Unlike some other languages, Java uses 2 bytes of memory to
represent characters.
• Java uses the Unicode standard, which allows for the use of
accented characters, unlike in C.
• Character constants are written between single quotes.
• Example:
char c = 'a' ;
18
The boolean Type
• This type is used to represent a logical value of true or false.
• In Java, you can have variables of this type, allowing
assignments like:
boolean exp ;
…
exp = n < p;
• The two boolean constants are true and false.
19
Type Conversion (Casting)
• Implicit conversions are allowed along the following
hierarchies:
byte → short →int→long→float→ double
char→ int→long→float→double
• Since Java is a strongly typed language, explicit type
conversion (casting) is sometimes necessary.
• In addition to numerical conversions, you can also force the
conversion of an object in a base class into an object in a
derived class (chapter 4: Inheritance).
20
Example
int a = 2 ;
// a = 2
double b = 2 ;
// b = 2.0 (implicit conversion)
int c = 18.7;
// incompatible types error
int d = (int) 18.7; //(explicit cast)
// d = 18
double e = 2/3;
// e = 0.0
double f = (double) 2/3;
// f = 0.666... 21
Default Values
Default values are assigned to uninitialized attributes of an object or elements of an
array.
Generally, the default value is zero or null, depending on the data type.
23
Application Programming Interface (API)
• Java SE provides a large number of classes that implement generic data and functionality
usable by many applications. These classes form the Java API.
Package
java.awt Graphical and interface management classes
java.lang Core classes (imported by default).
java.util Utility classes
javax.swing Other Graphical Classes
• These classes are organized into packages (libraries) dedicated to specific themes.
24
Accessing API classes
• To access a class from a specific package, you must first import that
class or its package.
For example, the Date class, which belongs to the java.util package
(and implements a set of methods for date manipulation), can be
imported in two (2) ways:
1. Import a single class from the package:
import java.util.Date ;
2. Import all classes from the package (including unused classes):
import java.util.* ;
25
« User Class » in Java
• In addition to API classes, a programmer can implement its own
classes (user types).
• A class groups together a set of fields/ attributes (data) and a set
of methods that operate on this data and/or on external data.
• Attributes can be either primitive or reference variables.
• The operations to be performed are programmed in the methods of
these classes, which can call methods from other classes.
• To create a class in Java, use the keyword « class ».
• Typically, you define at least one class, called the "executable"
class, which contains the main method.
26
Example of a Java class
public class Point {
int x; //abscissa
int y; //ordinates
27
Object instantiation in Java
• Object instantiation refers to the process of creating an
instance of a class (i.e., an object) in memory. This involves:
1. Allocating memory for the object (in the heap memory).
2. Initializing the object’s fields using a constructor (if defined).
28
Instantiation Example
public class Point {
…
Point (int abs, int ord) {
x = abs;
p is a reference
y = ord;
to the created
}
object
…
Point p = new Point(24, 5);
}
29
Object References (pointers) in Java
• In Java, the concept of pointers is transparent to the
programmer.
• However, it is important to know that any reference variable
representing an object is a pointer to that object, i.e. it
contains its memory address.
• This implies that passing objects as parameters to a method is
always pass-by-reference.
• On the other hand, passing primitive variables as parameters
is always pass-by-value.
30
Example
var 45
Heap Memory
p @100 x 24
@100
y 5
31
Example
var 45
Heap Memory
p x 24
y 5
32
Accessing attributes and methods
• Attributes (fields) represent the state of an object
• Methods represent the behaviour of an object
• To access an attribute or a method of an object in Java we use
the dot notation :
• Example:
p.x = 6;
p.move(3, 12);
33
Example
• If we want to invoke read method of the book object, which is
the most correct syntax:
(a) book.read()
(b) read.book()
(c) book(read)
34
Conditions for Accessing Attributes
and Methods
• To access an attribute or a method, three conditions must be
met:
1. The attribute or method being called exists!
2. The target object exists (is instantiated).
3. The object from which the call is made has the right to
access the method or attribute (visibility).
35
Object destruction
• Java allows memory allocation using the new operator to
instantiate objects. However, there is no operator to explicitly
destroy an object when it is no longer needed.
• To address this, Java relies on an automatic memory
management mechanism known as Garbage Collection (GC).
• The Garbage Collector is essential to prevent memory leaks,
which occur when memory is allocated but no longer used,
making it unavailable for other purposes.
• The Garbage Collector runs periodically during the execution
of a program to reclaim unused memory
36
Garbage Collector
• The Garbage Collector is a background process that
identifies and reclaims memory occupied by objects that are no
longer in use (i.e., unreachable objects).
• Java can determine, at any given moment, the number of
references to a specific object. This is possible because Java
always manages objects by reference. When there are no more
references to an object, it is guaranteed that the program can
no longer access it. As a result, the memory occupied by that
object can be freed.
• Java does not require this memory reclamation to happen
immediately. When an object has no remaining references, it is
considered eligible for garbage collection.
37
Arrays : Declaration
• In Java, an array is an object.
• An array object is declared as soon as square brackets ([]) are
present, either after its type (class or primitive type) or after
its identifier. The following two syntaxes are accepted for
declaring an array of integers:
int[] tab;
int tab[];
Note : Declaring an array simply specifies the type of its
elements and should never include dimensions. For example,
the following statement will be rejected by the compiler:
int tab[5];
38
Arrays : Creation
• Creating an array aims to allocate memory space. Java offers 2 ways to do
so: either (1) using the new operator or (2) using an initializer.
1. Creation using the new operator (as for objects)
Example :
int tab[] ;
tab = new int[5] ; // tab refers to an array of 5 integers
• The five created elements are initialized by default (as for all
objects fields) to a « null » value (0 for int). This is depicted as
follows:
tab 0 0 0 0 0
39
Arrays : Creation
2. Using an initializer :
Example :
int tab[] = {1, 2, 3, 5, 8};
• This assignment create an array of 5 int initialized with the
specified values. These values can be variables as well.
• Note :
This notation is possible only at the array declaration
40
Arrays Dimension
• When creating an array using the “new” operator, the value of the size is
only calculated at runtime:
• When the array is created its size is fixed and cannot be changed
• The array's size can be determined using the attribute length
• Exemple:
int t[] ;
t = new int[5] ;
System.out.println(« Size of t :"+t.length);//display 5
41
An array of objects example
• The elements of an array can be of any type (primitive or object).
• Here's an example of an array of type Point :
Point t [];
t=new Point[3];
t[0] = new Point (1,3);
t[1] = new Point (5,2);
t[2] = new Point (11,-6);
42
Using the for ...each loop
• The for ...each loop was introduced in JDK 5.0
Example: double t []={11,6,13,25};
for (double v :t) System.out.println(v);
• With this statement : System.out.println(v); the variable v will take the different
values of t, which is equivalent to :
for (int i = 0; i<t.length ; i++) System.out.println(t[i]) ;
• Note The for-each structure only applies to value consultations and cannot be used for
modifications
• Example :
With the statement for (double v : t) v=0; the values of t remain unchanged
43
Passing an array to a method
• When passing an array name as a method argument, you pass
the reference to the array. This implies that the method acts
directly on the concerned array and not on a copy.
• This also applies to an array provided as a return value. For
example:
44
Arrays of Arrays (or Multi-dimensional
Arrays)
• In Java, a multi-dimensional array is an array whose elements are
themselves arrays.
• A consequence of this is that rows can vary in length.
• This possibility actually offers greater flexibility since it allows
creating irregular arrays in which different rows can have different
sizes (jagged array).
• Of course, we can still create regular multi-dimensional arrays with
uniform row lengths (rectangular arrays or matrix).
45
Arrays of Arrays: Dimension
• The number of square brackets ([]) indicates the number of
dimensions of the array.
• For example:
int[] represents a one-dimensional array.
int[][] represents a two-dimensional array.
int[][][] represents a three-dimensional array, and so on.
46
Arrays of Arrays: Declaration and
initialization
• There are different ways and syntaxes when
declaring an array of arrays.
• These are 3 equivalent declarations :
int tab[][];
After these
int[][] tab; declaration the array
is not created yet
int []tab[];
We can also use this syntax for the declaration :
int t[][] = {new int [3], new int [2]};
t
This statement allows creating a jagged array with
two rows: the first row is an array of three integers
and the second row is an array of 2 integers, as shown
in the following diagram:
0 0 0 0 0
47
Arrays of Arrays: Declaration and
initialization
• An array of arrays can also be declared and initialised as follows if we
consider the same example:
• int t[][] = new int [2][]; t
48
Arrays of Arrays: Declaration and
initialization
• t[0] is the reference to the first array of 3 integers.
• t[0][1] is the 2nd element of this array.
• t[1] is the reference to the second array of 2 integers.
• t[1][i-1] is the i-th element of the second array.
• The expression t.length equals 2
• The expression t[0].length equals 3
• The expression t[1].length equals 2
49
Example
• Write a program that creates an array with 3 rows, where the
number of columns corresponds to the row number:
• Row 1 → 1 column
• Row 2 → 2 columns
• Row 3 → 3 columns
• The cells of this array will be initialized with the sum of the
row index and the column index.
50
Example
public static void main(String[] args) {
int i, j;
int tab[][] = new int [3][];
for(i=0; i<tab.length;i++) {
tab[i] = new int[i+1];
for(j=0;j<tab[i].length;j++)
tab[i][j]=i+j;
}
}
51
Case of rectangular arrays (matrix)
• In rectangular arrays all rows have the same size.
• To create rectangular arrays, Java allows this syntax:
int tab[][] = new int [nRow][nCol];
52
Example of a rectangular array
• Write a Java code that creates a matrix with 2 rows and 3
columns
• Each cell of this matrix is initialized with the sum of the row
index and the column index
53
Example of a rectangular array
public static void main(String[] args) {
int i, j;
int tab[][] = new int [2][3];
for(i=0; i<tab.length;i++)
for(j=0;j<tab[i].length;j++)
tab[i][j]=i+j;
54
Arrays of Arrays & for .. each loop
• What will the code from the previous example display?
public static void main(String[] args) {
int i, j;
int tab[][] = new int [2][3];
for(i=0; i<tab.length;i++)
for(j=0;j<tab[i].length;j++)
tab[i][j]=i+j;
for(int v[] :tab) {
for(int w : v) {
System.out.print(w+ " ");
}
System.out.println();
}
}
55
Strings in Java
• Strings are not considered in Java as a primitive type or as an
array.
• A specific class, called String, is used, provided in the
java.lang package.
• Objects of the String class have the following characteristics:
• Their values cannot be modified (immutable) in memory.
• The + operator can be used to concatenate two strings
56
Strings Creation
• In Java, strings can be created in two main ways:
Using string literals.
Using the new keyword
57
Strings Creation
(1) Using string literals :
String ch = "hello"; // declare a String variable containing a
reference to the String "hello"
ch "hello"
58
Example
String ch1 = new String();
String ch2 = new String("hello");
String ch3 = new String(ch2);
• ch1 refers to a String object that represents an empty
string ("")
• ch2 refers to a String object that contains the value
"hello "
• ch3 refers to a String object that is a copy of the content
of ch2. Since ch2 contains "hello", ch3 will also contain
"hello". However, ch3 is a separate object in memory,
distinct from ch2
59
String Literals vs. new String() in
memory
• When creating a string using a string literal, Java stores it
in a special memory area called the string pool (Heap
memory).
• The string pool is a mechanism to optimize memory usage by
reusing identical strings. If a string with the same value
already exists in the pool, the new reference will point to the
same object in the pool.
Example:
String str1 = "value 1";
String str2 = "value 1";
str1 and str2 refer to the same object in the string pool
60
String Literals vs. new String() in
memory
• When creating a string using the new keyword, Java creates a
new object in the heap memory, even if a string with the same
value already exists in the string pool.
• Example:
String str1 = new String("hello");
• str1 and str2 are two distinct objects in memory, even though
they have the same value ("hello").
61
String comparison
• Comparing strings using the == or != operators only compares the
references to those strings.
• Two strings with different values will always have different references.
However, two strings with the same value do not necessarily correspond to
the same object.
• When comparing strings, we should use the equals() method to compare
their content, not the == operator, which compares references.
• The String class provides an equals() method that compares the content of
two strings.
• Example : String ch = "hello";
System.out.println(ch.equals("hello")); //displays true
62
Strings: Immutable Objects
• String objects in Java are immutable, meaning their content
cannot be changed after creation.
• Operations that appear to modify a String actually create a
new String object.
• Immutability provides benefits such as thread safety, security,
and performance optimization.
63
Strings: Immutable Objects
• Example :
String str = "old value";
"new value"
64
Strings: Immutable Objects
• Example :
String str = "old value";
"new value"
65
String class methods
• Because of its immutable nature, several methods in the
String class return new String objects that are the result of
modifying the original string’s value.
• Some of these methods are listed below:
String concat (String str): Returns a new string consisting of this
string concatenated with str.
String toLowerCase (): Returns a new string identical to this string
except all uppercase letters are converted to their lowercase
equivalent.
String toUpperCase (): Returns a new string identical to this string
except all lowercase letters are converted to their uppercase
equivalent.
…
66
String Length
• The length()method is used to get the length of a string, i.e.,
the number of characters it contains.
• Examples:
String ch = "";
int n = ch.length(); // n contains 0
String ch1 = "Good morning";
n = ch1.length(); // n contains 12
67
Java and Modularity
• Modular programming consists of breaking down a problem
into a set of sub-problems or modules. Object-oriented
programming is highly modular because each object is a
module.
• In Java, this modular decomposition occurs on several nested
levels:
• A package contains classes related to the same theme
• A class contains attributes and methods
• A method has parameters and a block of statements
• A block of statements contains local variables and other
blocks...
68
Package Concept
• This concept corresponds to a logical grouping of a set of
classes under a common identifier.
• This concept is similar to libraries found in other programming
languages.
• This concept facilitates the development of large software by
allowing related classes to be distributed across different
packages.
• The risk of creating two classes with the same name is limited
only within the same package.
69
Defining a Package in Java
• Define a package requires to include a package command as the
first statement in a Java source file:
package myPackage;
• For example, if the public class Class1 is included in package p1,
then the source file Class1.java must mandatorily begin with the
statement: package p1;
• The package statement must be the first line of code in the file
(except for comments)
• If no package is specified, the class belongs to the default (unnamed)
package
• Package names should be all lowercase by convention
• Package names are typically organized in a hierarchical manner
(e.g., com.company.project)
70
Using a Class from a Package
• When a program references a class, the compiler looks for it in
the default package.
• To use a class belonging to another package, it is necessary to
either:
1. Use the class’s fully qualified name which includes its full
package hierarchy.
2. Use the import statement by citing either a specific class
from a package or the entire package
71
(1) Class’s fully qualified name
• if the Rectangle class belongs to the package FormeGeo, we can
use its fully qualified name any place we use the class name :
FormeGeo.Rectangle rec = new FormeGeo.Rectangle();
…
rec.display(); // here the package name is not required
72
(2) Use import statement
• In a Java source file, import statements occur immediately following
the package statement (if it exists) and before any class definitions.
This is the general form of the import statement:
import pkg1 [.pkg2].(classname | *);
• Java includes the import statement to bring certain classes, or
entire packages, into visibility. Once imported, a class can be
referred to directly, using only its name.
• For example : import FormeGeo.Rectangle, ForGeo.Square;
• With this instruction, we can use the Rectangle and Square classes
without having to mention their package names.
• If a number of classes in the same package are to be imported,
simply use the instruction: import FormeGeo.*
• All classes in the FormeGeo package can be used.
73