0% found this document useful (0 votes)
23 views52 pages

Java Programming Basics Explained

The document outlines a course on Java programming, detailing fundamental concepts such as variables, data types, control structures, and program structure. It explains the importance of variables, their declaration, and initialization, as well as primitive types like integers, real numbers, booleans, and characters. Additionally, it covers control structures for conditional and iterative execution of code, providing examples of programming syntax and structures.

Uploaded by

Stev Dassi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views52 pages

Java Programming Basics Explained

The document outlines a course on Java programming, detailing fundamental concepts such as variables, data types, control structures, and program structure. It explains the importance of variables, their declaration, and initialization, as well as primitive types like integers, real numbers, booleans, and characters. Additionally, it covers control structures for conditional and iterative execution of code, providing examples of programming syntax and structures.

Uploaded by

Stev Dassi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

INF151

INTRODUCTION TO SOFTWARE ENGINEERING

Course Lecturer: Dr. KIMBI Xaveria

Academic Year.................................................................................................2025-2026
MODULE VI: INTRODUCTION TO
JAVA LANGUAGE
Course Objectives

Understand the basics of programming in Java.


Write Java programs from the simplest to the
most complex.
ELEMENTARY NOTIONS
What is a program?

The goal of programming is to create software or programs. These


consist of a set of processes that transform numerical data (inputs)
into other numerical data (outputs). The output data can be
displayed in a graphical form (with windows like those in programs
such as Word and Excel) or more simply displayed in a console as
text.

What happens to the computer when a program is executed? It


reads the executable file of the program as a sequence of 0s and 1s
(binary coding) and executes the coded instructions one after the
other. This sequence of 0s and 1s is called machine language and is
directly executable by the computer's microprocessor.
ELEMENTARY NOTIONS
What is a program?

Compilation Execution
$ javac [Link] [Link] $ java Bonjour
ELEMENTARY NOTIONS
VARIABLES

Variables are the most important aspect of programming, as they


allow us to store data in a memory location and transform it using
operators. One can think of a variable as a label associated with a
unique box in which a value of a certain type (integer or real, for
example) is stored.

Before using a variable, it is necessary to declare it, which means


associating the variable with a memory location and specifying its
type. The size of the memory location (in bytes, i.e., 8 bits) and the
binary coding of the value will be determined based on the type of
the variable. The declaration is done with an instruction of the form:
ELEMENTARY NOTIONS
VARIABLES

Variables are the most important aspect of programming, as they


allow us to store data in a memory location and transform it using
operators. One can think of a variable as a label associated with a
unique box in which a value of a certain type (integer or real, for
example) is stored.

Before using a variable, it is necessary to declare it, which means


associating the variable with a memory location and specifying its
type. The size of the memory location (in bytes, i.e., 8 bits) and the
binary coding of the value will be determined based on the type of
the variable. The declaration is done with an instruction of the form:
typeVariable nomVariable;
ELEMENTARY NOTIONS
VARIABLES

The variable nomVariable is of type typeVariable. It is associated with


a memory location that contains a value that needs to be initialized.
This is done using the assignment operator "=":
nomVariable = aValue;

The assignment writes the value aValue into the memory location
associated with nomVariable. We say that nomVariable "takes the
value" aValue.
aValue must be compatible with the type of nomVariable. For
example, if typeVariable is an integer, aValue must be an integer
value. One can draw a parallel between the type of a variable and the
unit of measurement of a physical quantity that specifies the nature
of the manipulated quantity.
ELEMENTARY NOTIONS
VARIABLES

We can also declare and initialize a variable in a single instruction:


typeVariable nomVariable = aValue;

Next, we will detail the four so-called "primitive" types, which are
directly accessible in memory (unlike non-primitive types that we will
see in section 3), meaning that the value assigned to the variable is
stored in the memory location associated with it. For each of these
types, we will also see the operators that can be applied to variables
of this type to transform their value.
ELEMENTARY NOTIONS
PRIMITIVE TYPES

There are 4 categories of primitive types (integer, real, boolean,


character). The range of representable values for each type may vary
depending on the memory space they occupy.

INTEGERS

In Java, all types that represent integers are signed. Thus, on n bits,
we can code integers from −(2^(n−1)) to 2^(n−1) − 1. Negative values
are encoded in two's complement. For more information on this
encoding, we refer you to the numeral systems course available on
the CIPC page.
ELEMENTARY NOTIONS
INTEGERS

The different types of integers are as follows:

Name Size Representable Range

byte 1 byte [-128 ... 127]


short 2 bytes [-32768 ... 32767]

int 4 bytes [-2^31 ... 2^31 - 1]

long 8 bytes [-2^63 ... 2^63 - 1]


ELEMENTARY NOTIONS
INTEGERS
We can apply arithmetic operators (+, -, *, /) to two integer-type
variables or expressions (composition is possible as in
mathematics). The result of this operation is also of integer type
(which allows composition).
When both operands are of integer type, the operator / calculates
integer division and the operator % calculates the remainder of
this division.
Example:
int valA = 7;
int valB = 2;
int valC = valA / valB; // valC contains the value 3
int valD = valA % valB; // valD contains the value 1
ELEMENTARY NOTIONS
REAL NUMBERS
The description of real number encoding is covered in the
numeral systems course on the CIPC page. In Java, there are two
types of representation for real numbers: single and double
precision (respectively float and double).

Name Size Representable Range

float 4 bytes [-3.4 × 10^38, ..., -1.4 × 10^-45, 0, 1.4 × 10^-45, ..., 3.4 × 10^38]

double 8 bytes [-1.8 × 10^308, ..., -4.9 × 10^-324, 0, 4.9 × 10^-324, ..., 1.8 × 10^308]
ELEMENTARY NOTIONS
REAL NUMBERS

When at least one of the operands is of a real type, the / operator


performs real division.
Example:
double reelA = 7;
double reelB = 2;
double division = reelA / reelB; // The variable division contains
the value 3.5
ELEMENTARY NOTIONS
BOOLEAN VALUES
A very useful variable type in computer science is the boolean
type, which takes two values: TRUE or FALSE.

Name Size Representable Range


Representable
Name Size
Range

booleanboolean 1 byte
1 byte [true,false]
[true,false][true,false]

Logical operators (and, or, not) can be applied to boolean variables or


expressions. The result of this operation is also of the Boolean type.
&& denotes the logical AND operator
|| denotes the logical OR operator
! denotes the logical NOT operator (which transforms a value of
true to false and vice versa)
ELEMENTARY NOTIONS
BOOLEAN VALUES
Truth Table Example:

a b a && b a b a || b
FALSE FALSE FALSE FALSE FALSE FALSE
FALSE TRUE FALSE FALSE TRUE TRUE
TRUE FALSE FALSE TRUE FALSE TRUE
TRUE TRUE TRUE TRUE TRUE TRUE

boolean boolA = true;


boolean boolB = false;
boolean nonA = !boolA; // nonA is false boolean
A And B = boolA && boolB; // A And B is false
ELEMENTARY NOTIONS
CHARACTERS
The character type can correspond to any symbol on the
keyboard (uppercase or lowercase letters, digits, punctuation,
and symbols).

Name Size Representable Range


[a...z,A...Z,0...9,:,;,.,?,!,...]
char 2 bytes
[a...z,A...Z,0...9,:,;,.,?,!,...]

To distinguish the value corresponding to the character a from the


variable named a, an apostrophe is used for the former.
char character = 'a'; // The variable “character” contains the value 'a'
int a = 3; // The variable a contains the value 3
CONVERSIONS

Like any numeric data, a character is encoded as a sequence of 0s


and 1s that can be interpreted as an unsigned integer. In some
contexts, it is useful to manipulate this code directly. The variable
of type char can be converted into a variable of type int, as
explained below.

The conversion (also called type casting) of one primitive type to


another is done as follows:
typeVariableA variableA = (typeVariableA) valueB;
CONVERSIONS

If variableA and valueB are not of the same type, this statement
assigns to variableA the conversion of the value of valueB to the
type typeVariableA :
Integer to Real: the same value coded as a real number
Real to Integer: the integer part of the real number
Integer to Character: the character whose code is the integer
Character to Integer: the numeric code corresponding to the
character

int i;
double x = 2;
i = (int) (x * 42.3); // i is 84
COMPARISON OPERATORS
Comparison operators allow you to compare two variables of the
same primitive type (integer, floating-point, boolean, and
character) and return a boolean value:
Operator Description
"===" equality comparison
!= not equal
< strictly less than
less than or equal (written as
<=
pronounced)
> strictly greater than
greater than or equal (written as
>=
pronounced)
COMPARISON OPERATORS

Note: The operator = corresponds to assignment, while the


operator == corresponds to equality comparison, which is the
same as the = sign used in mathematics!
Composite expressions must be fully parenthesized:
double a = 8;
boolean estDansIntervalle = ((a >= 0) && (a <= 10)); // is true if and
only if a belongs to [0, 10]
THE PROGRAM
In general, the structure of a simple program is always the same. This basic
structure must be memorized, as it forms the skeleton of the program. It is
advisable, when creating a program, to start by writing this structure.
Indeed, once this structure is created, the program is functional: it can be
compiled and executed. Of course, at this stage, the program does strictly
nothing since there are no instructions, only comments.

public class Example {


// Example is the name of the program
// written in the file [Link]
public static void main(String[] args) {
// block of program instructions
// executed when the program is launched
}
}
THE PROGRAM
Declare and initialize two variables, celsius and fahrenheit, with fahrenheit
calculated from celsius, and then display them on the screen.

public class ConversionCelsiusToFahrenheit {


public static void main(String[] args) {
double celsius = 12.0;
double fahrenheit = ((9.0 / 5.0) * celsius) + 32.0 ;
[Link](celsius);
[Link](" degrees Celsius converted to Fahrenheit is ");
[Link](fahrenheit);
}
}

The [Link] statement allows you to display the value of a


primitive type variable or a text enclosed in quotes.
CONTROL STRUCTURES
The principle of a program is to modify the content of variables using the
basic instructions we have just seen (assignment and operators). However,
we may want these instructions to be executed only under certain
conditions, or we may want to repeat the execution of these instructions.
Control structures allow us to specify whether the execution of a process is
conditional or if it is performed repeatedly.

BLOCK OF INSTRUCTIONS
Curly braces {} are used to delimit a block of instructions, which is a set of
instructions that will be executed one after the other. A block of
instructions can, for example, be executed only when a condition is met, or
it can be executed multiple times in succession. It is the conditional and
iterative control structures that allow us to express this. Variables declared
within a block are accessible only within that block.
CONTROL STRUCTURES
BLOCK OF INSTRUCTIONS
Two variables with the same name can be declared in two distinct blocks.
These are two different variables associated with two different memory
locations. Thus, their values are generally different. Confusing one with the
other can be a source of programming errors.

CONDITIONAL STRUCTURES

Conditional control structures allow you to specify under what conditions a


block of instructions will be executed. This condition is expressed by a
logical expression.
CONTROL STRUCTURES
THE ALTERNATIVE STRUCTURE

The first type of conditional is written as follows:


if (condition) {
// equivalent to (condition == true)
// block of instructions executed if the condition is true
} else {
// block of instructions executed if the condition is false
}
This control structure expresses an alternative. However, it may be desired
for a block to be executed under a certain condition and, otherwise, no
instruction to be executed. In this case, the else clause and its block are
omitted. The parentheses around condition, which is a variable or a boolean
expression, are mandatory.
CONTROL STRUCTURES
THE ALTERNATIVE STRUCTURE

Display a message if the temperature is above 50:


public class WhatUnit {
public static void main(String[] args) {
int temperature = 36;
if (temperature > 50) {
[Link]("The temperature is probably in Fahrenheit");
}
}
}
CONTROL STRUCTURES
THE MULTIPLE CHOICE STRUCTURE
The second type of conditional allows for multiple value tests on the content of
the same variable. Its syntax is as follows:
switch (variable) {
case value1:
// list of instructions executed if (variable == value1)
break;
case value2:
// list of instructions executed if (variable == value2)
break;
...
case valueN:
// list of instructions executed if (variable == valueN)
break;
default: // list of instructions executed otherwise
}
CONTROL STRUCTURES
THE MULTIPLE CHOICE STRUCTURE

The default keyword precedes the list of instructions that are executed when
variable has a value different from value1, ..., valueN. The break keyword indicates
that the list of instructions is complete.

ITERATIVE STRUCTURES
There are three forms of iterative structures, each with a specific use case that we
will see.
REPEATED ITERATION n TIMES
The first iterative form is the for loop. It allows you to repeat a block of instructions
a fixed number of times. In its syntax, you need to declare and initialize the variable
that serves as the loop counter, specify the condition on the counter for which the
loop stops, and finally provide the instruction that increments or decrements the
counter:
ITERATIVE STRUCTURES

REPEATED ITERATION n TIMES

for (int counter = 0; counter < n; counter = counter + 1) {


// block of instructions repeated n times
}
or
for (int counter = n; counter > 0; counter = counter - 1) {
// block of instructions repeated n times
}
ITERATIVE STRUCTURES

REPEATED ITERATION n TIMES


Display the Fahrenheit conversion of Celsius degrees from 0 to 39:
public class CelsiusToFahrenheitConversion {
public static void main(String[] args) {
for (int celsius = 0; celsius < 40; celsius = celsius + 1) {
double fahrenheit = ((9.0 / 5.0) * celsius) + 32.0;
[Link](celsius);
[Link](" degrees Celsius converted to Fahrenheit is ");
[Link](fahrenheit);
}
}
}

The for loop is used when you know in advance the number of repetitions to
perform.
ITERATIVE STRUCTURES

REPEATED ITERATION WHILE A CONDITION IS TRUE


The second iterative form is the while loop. It executes the block of instructions as
long as the condition is true. The block may never be executed. The syntax is as
follows:
while (condition) {
// equivalent to (condition == true)
// block of instructions repeated while the condition is true.
// the condition must be modified in this block
}

This structure executes the block of instructions as long as (while in English) the
condition holds true.
It is important to always ensure that the condition will eventually become false
during an iteration of the iterative structure. Otherwise, the program's execution
will never stop.
ITERATIVE STRUCTURES

REPEATED ITERATION WHILE A CONDITION IS TRUE


Display the conversion from Celsius to Fahrenheit as long as the conversion is less than
100:
public class CelsiusToFahrenheitConversion {
public static void main(String[] args) {
int celsius = 0;
double fahrenheit = ((9.0 / 5.0) * celsius) + 32.0;
while (fahrenheit < 100) {
[Link](celsius);
[Link](" degrees Celsius converted to Fahrenheit is ");
[Link](fahrenheit);
celsius = celsius + 1;
fahrenheit = ((9.0 / 5.0) * celsius) + 32.0;
}
}
}
ITERATIVE STRUCTURES

REPEATED ITERATION WHILE A CONDITION IS TRUE


The while loop is used when the number of iterations is not known in advance but can be
expressed through a boolean expression that becomes false when the repetition should
stop.

ITERATION EXECUTED AT LEAST ONCE


The third form of iteration is the "do while" loop. It is a variant of the while loop, where the
stopping condition is tested after the instructions have been executed:
do {
// block of instructions executed
// condition must be modified in this block
} while (condition); // if the condition is true,
// the block is executed again

Do not forget the ; after the stopping condition. The block of instructions is executed at
least once.
ITERATIVE STRUCTURES

ITERATION EXECUTED AT LEAST ONCE


Display the conversion from Celsius to Fahrenheit until the Fahrenheit degree is greater
than or equal to 100:

public class CelsiusToFahrenheitConversion {


public static void main(String[] args) {
double fahrenheit;
int celsius = 0;
do {
fahrenheit = ((9.0 / 5.0) * celsius) + 32.0;
[Link](celsius);
[Link](" degrees Celsius converted to Fahrenheit is ");
[Link](fahrenheit); celsius = celsius + 1;
} while (fahrenheit < 100);
}
}
METHODS

A method is a block of instructions that can be executed by simply calling the method
from the main program block (the main method) or from another method. Methods
allow you to execute the same block of instructions in multiple parts of the program.
You might create a method in two scenarios:

To group a set of instructions that contribute to accomplishing the same task. This
makes the program more readable and understandable for another person (or for
yourself during the next lab session) and facilitates debugging (corrections and
testing). This block of instructions is associated with a name that is chosen in relation
to the processing performed by the method.

To group a set of instructions that are repeated in different places in the program
(unlike iterative forms that repeat the block of instructions consecutively).
The role of a method is to process data. This means that, in general, the method
performs a processing operation based on the input data and returns a result
METHODS
PREDEFINED METHODS

In Java, there are many predefined methods. The most well-known is probably the
following method, which allows you to display a string on the screen:
[Link]("the string to display");

Other examples of methods you can use are those from the Math library: sqrt, cos, sin,
abs, etc. When calling a method, you use its name followed by the list of its actual
parameters (separated by commas) in parentheses:
methodName(parameter_1, ..., parameter_n);

If this method returns a result, you must assign this result to a compatible type
variable in order to use it later:
double root = [Link](5.2);
METHODS
PROPER METHODS: DECLARATION OF A METHOD

The definition of a method is called a declaration. The syntax for declaring a method is
as follows:
static ReturnType methodName(Type1 param1, ..., TypeN paramN) {
// block of instructions
return returnedValue;
}
The fact that you must precede the declaration of a method with the keyword "static" is
explained on page 15. ReturnType is the type of returnedValue, the value returned by the
method. If the method does not return any value, the keyword void is used instead of the
return type.

For reasons unknown to teachers, there is often confusion between returning a value
and displaying it.
METHODS
PROPER METHODS: DECLARATION OF A METHOD

The parameters correspond to the input data for the method. In the declaration, the
parameters are called "formal": they are variables that represent each input data. You
can draw an analogy here with the variable x used in mathematics when defining a
function f(x). Parameters are optional, but if there are no parameters, the parentheses
must remain present.

PROPER METHODS: CALLING A METHOD

It is at the moment of calling the method that the formal parameters are initialized,
meaning that a value is assigned to them. The "actual" parameters of the call, those
passed as arguments to the method at the time of the call, are assigned to the formal
parameters of the method (those in the method definition) by position:

the value of the first actual parameter is assigned to the first formal parameter, and so
on. The actual parameters can be values or variables.
METHODS
PROPER METHODS: CALLING A METHOD

static int addition(int x, int y) {


// x and y are the formal parameters
return x + y;
}
public static void main(String[] args) {
int a = 7;
int sum = addition(a, 3);
// a and 3 are the actual parameters of the call
// x takes the value of a and y takes the value 3
}

In Java, parameter passing is done by value, meaning that the value of the actual
parameter is assigned to the formal parameter. Thus, if the value of the formal
parameter is modified in the method block, this modification is local to the method and
does not affect the calling context.
METHODS
RECURSIVE METHODS

We previously stated that a method can call another method within its block. It is also
possible for a method to call itself. At first glance, this may seem limited, but
recursion allows for certain mathematical calculations, particularly with sequences
defined by recurrence. For example, we can calculate the factorial of an integer using
recursion. To do this, we can proceed as follows if we want to calculate the factorial
of 4:
4!=4×3! 3!=3×2!
2!=2×1! 1!=0! 0!=1

In this calculation, we see a recurrence: to calculate 4!, it is sufficient to calculate 3!,


then 2!, and so on, until reaching a directly resolved case (the base case without
recursive expression). We can then create a method calculateFactorial that takes an
integer nn as a parameter and returns the integer n!.
METHODS
RECURSIVE METHODS
It is clear that the function simply needs to call itself following the same principle to easily calculate
the factorial of any integer. However, when calculating 0!, it is necessary for the function to directly
return the value 1 without making a recursive call. In other words, the call to calculateFactorial(0)
should not trigger a call to calculateFactorial(-1). It should return 1 directly to avoid an infinite
number of calls:

public class Factorial {


static int calculateFactorial(int n) {
if (n > 0) {
// general case
return n * calculateFactorial(n - 1);
} else {
// base case or stopping
casereturn 1;
}
}
public static void main(String[] args) {
int value = 4;
[Link](calculateFactorial(value)); // 5 calls in total
}
}
METHODS
RECURSIVE METHODS: AN EXAMPLE
The following example presents a program with two methods: CelsiusToFahrenheit converts
valueToConvert, a real value representing a temperature in degrees Celsius, into a temperature in
degrees Fahrenheit. The value in Fahrenheit is returned by the method. CelsiusToKelvin converts
valueToConvert, a real value representing a temperature in degrees Celsius, into a temperature in
degrees Kelvin. The temperature in Kelvin is displayed, and no value is returned by the method.

Observe the difference between the calls to the two methods in the main: the value returned by
CelsiusToFahrenheit is assigned to the variable temperature, which is then displayed. The
CelsiusToKelvin method is called directly without assigning its return value since it does not return
one (the void keyword in the declaration).

The program considers integer temperatures in degrees Celsius from 0 to 39 inclusive. Every other
time, its conversion to degrees Fahrenheit is displayed; the other time, its conversion to degrees
Kelvin is displayed. Note the change in the value of the variable calculateFahrenheit at each loop
iteration.
METHODS
RECURSIVE METHODS: AN EXAMPLE
public class Conversion {
static double CelsiusToFahrenheit(double valueToConvert) {
double Fahrenheit = ((9.0 / 5.0) * valueToConvert) + 32.0;
return Fahrenheit;
}
static void CelsiusToKelvin(double valueToConvert) {
double Kelvin = 273.15 + valueToConvert;
[Link](Kelvin);
}
public static void main(String[] args) {
boolean calculateFahrenheit = true;
for (int celsius = 0; celsius < 40; celsius = celsius + 1) {
if (calculateFahrenheit) {
double temperature = CelsiusToFahrenheit(celsius);
[Link](temperature);
} else {
CelsiusToKelvin(celsius);
}
calculateFahrenheit = !calculateFahrenheit;
}
}
}
NON-PRIMITIVE TYPES
GENERALITIES

We saw in section 1.2 that a variable allows us to store a piece of data of a certain
type in a memory location, and that this data can be transformed using specific
operators of its type. However, instead of manipulating a single value, it is often
much more convenient for a variable to be associated with a collection of values.
This is what non-primitive types, called objects in Java, allow.

Suppose we want to create a program that automatically writes letters to


subscribers of a library. For each subscriber, we know their first name, last name,
the number of volumes borrowed, and the number of days since the borrowing.
We then need to handle hundreds of subscribers, each described by four values,
some of which (first name, last name) are also a collection of primitive values (a
sequence of characters). This type of processing is impossible using only primitive
types.
NON-PRIMITIVE TYPES
GENERALITIES

Just as specific operators are associated with each primitive type, it can be useful
to define operators or methods that allow us to query or transform the values of
these objects. We want to have a method isLate that returns the list of subscribers
whose last borrowing was made more than 21 days ago.

In this section, we will introduce the concepts related to objects necessary for
creating such a program. First and foremost, we will explain the common
mechanisms for all Java objects, that is, how an object is stored in memory and
how it is instantiated, meaning how we reserve the necessary memory location for
the object. We will also see how comparison operators work on objects.
NON-PRIMITIVE TYPES
STORAGE OF OBJECTS IN MEMORY

Just like primitive type variables, an object type variable is associated with a
fixed-size memory location that contains a single value. This memory location
stores a value of type address that indicates the address of the memory location
where all the values of the object are stored contiguously. Thus, the variable is
linked to the data indirectly: it contains the address at which the data can be
found. The variable being manipulated is actually a reference to the memory
location where all the data resides.

address 0001 0012 maVariable


... ...
address 0012 value1
address 0013 valeu2
address 0014 valeur3
address 0015
NON-PRIMITIVE TYPES
INSTANTIATION OF OBJECTS

The instantiation of an object is done using the new keyword, which "reserves" the
necessary memory location to store all the values of the object, that is, a set of
contiguous memory slots, and returns the address of the first memory slot.

// Declaration and instantiation


ObjectType myVariable = new ObjectType();

COMPARISON OF TWO OBJECTS


When comparing two objects using the operators ==, <=, >=, <, or >, the addresses
of the objects are compared. Thus, the == operator returns true if both variables
refer to the same memory location, hence the same object.

if (variableA == variableB) {
[Link]("Both variables reference the same object.");
}
NON-PRIMITIVE TYPES
ARRAYS

Arrays allow us to group a set of values of the same type.


ONE-DIMENSIONAL ARRAYS
A one-dimensional array is a linear collection of elements of the same type. Each
element of an array is identified by an index and contains a value. The indices of
an array start at 0. Consequently, an array of nn elements will have indices
ranging from 0 to n−1.

The type of the elements in the array is chosen during the declaration of the
array. However, the size of the array is not part of its type and will be defined
during the instantiation of the array. The declaration of an array is done with the
syntax [].

int[] tabInt; // Declaration of an integer array


char[] tabChar; // Declaration of a character array
NON-PRIMITIVE TYPES
ONE-DIMENSIONAL ARRAYS

Instantiation specifies the size to reserve. It is done with the new keyword.
int[] tabInt; // Declaration of an integer array
tabInt = new int[10]; // Instantiation of an array of 10 integers

Note that it is possible, in the case of initialization only, to describe the entire
array in the form of a value list. This automatically initializes the array with the
appropriate number of cells, and the values are stored in the different slots.
int[] tabFive = {12, 33, 44, 0, 50}; // Express initialization

Once the array is initialized, we access the elements of the array using the
following syntax:
int i = 0;
int value1 = tabFive[i]; // Returns 12, the element at index 0
int value2 = tabFive[4]; // Returns 50, the element at index 4
NON-PRIMITIVE TYPES
ONE-DIMENSIONAL ARRAYS

Once initialized, it is possible at any time to know the size of an array (its number
of slots) using the following syntax:
int size = [Link]; // Returns 5, the number of slots in the tabFive array

MULTI-DIMENSIONAL ARRAYS

A two-dimensional array is a special case of one-dimensional arrays. Indeed, it is


simply an array where each element contains a one-dimensional array of
elements. By recurrence, it is therefore possible to define an array of nn
dimensions. From a notation perspective, each dimension corresponds to an
additional pair of brackets at the type and access level.

char[][] T;
T = new char[3][5]; // Declaration of a two-dimensional array of characters
// Instantiation of an array containing 3 arrays of 5 characters each. T thus has 3
rows and 5 columns.
NON-PRIMITIVE TYPES
MULTI-DIMENSIONAL ARRAYS

The multiple brackets are read from left to right, which corresponds to viewing
the arrays from the outermost to the innermost. Thus, [Link] returns 3, the size
of the outer array, while T[0].length returns 5, the size of the array contained in
the first slot of T. This follows the same convention as in mathematics for
matrices, first rows, then columns. Finally, since each dimension is an array, it
follows that each dimension is indexed from 0 to n−1.

int[][] T = new int[5][5];


int i = T[0][1]; // i equals 154
int[] T1 = T[1]; // T1 refers to the array [12, 15, 45, 37, 789]

You might also like