Java Programming Guide for Beginners
Java Programming Guide for Beginners
TPbooklet
Object-Oriented Programming
Java Language
Aymen Ferjani
[Link]@[Link]
TP4: H´
Inheritance, Polymorphism and Abstract Class 13
TP5: ImplementationImplementation
´ of interfaces and exception handling 18
TPbooklet Department of Computer Science
and Telecoms
Object-Oriented Programming Level: 2m̀eSEIoT/IRS
1 Course Concepts
1.1 Compilation and execution of a Java program
Before starting to write Java code, it is necessary to install a JDK (Java Development Kit)
development Kit) in order to compile and execute our code.
The writing of a Java source code must be done in a file with the .java extension.
compiling this will generate another file with the .classet extension that contains some
pseudo-code. It is this file that is interpreted and executed by the Java Virtual Machine (JVM).
The JVM is an integral part of the JDK.
The compilation and execution of a Java file can be done in two different ways,
either with an IDE (Integrated Development Environment), or with a console.
A Java source file contains one or more classes, but only one declared class.
public. The name of the file must correspond to the name of this class.
If the developed project consists of a single file, then it must necessarily contain
the main method.
In procedural programming, methods are viewed as functions.
The main method must always have the following signature:
Type Significance
char Character
boolean Bool´een
Remark
There are also the types byte, short, and long, which are integer types.
We also find the float type which represents a real number.
For character strings, it is preferable to use the String class (which is not a
primitive type).
int[]tab={20,-9,13,100,5};
Iterate and display each element of the array tab
for(int x: tab) {
[Link](x);
}
2 practical exercises
For each exercise, a new project will be created.
Exercise 1
Create the class Hello with the following code, then test it:
Exercise 2
Create the class Ex2, then:
´
1. Write the method public int addition(int x, int y, int z) that returns the sum of 3
integers x, y, z.
2. Add the method public int max(int x, int y, int z) that returns the maximum between
3 integers x, y, z.
3. Add the method public boolean prime(int x) that verifies if x is a number
first or not.
4. Test these 3 methods as follows:
import [Link];
public class Ex2 {
Definitions of the methods for questions 1, 2, and 3
...
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
inta, b, c;
Give 3 integers:
a = [Link]();
b = [Link]();
c = [Link]();
Ex2 obj=newEx2();//Creation ofan instance of the Ex2 class
[Link](a+"+"+b+"+"+c+"="+[Link](a, b, c));
[Link]("The maximum of the 3 integers is " + [Link](a, b, c));
if([Link](a)) {
[Link](a + " is a prime number");
}
else{
[Link](a + " n");is not a prime number);
}
}
}
Exercise 3
Ẃrite a program that calculates and displays the sum and product of 4 integers provided.
arguments.
For each argument, use the predefined method [Link](x) to obtain a
entire from this argument.
Exercise 4
´
Write a program to read a positive integer entered in the command line
and display it in binary format.
Objectives
Input of values.
Passing values in command line (arguments).
Utilization of conditional and iterative structures.
Manipulation of the tables.
1 Course Concepts
1.1 Creation and manipulation of a fixed-size array
Creating a fixed-size array is done by the following instruction:
type[]nomTableau=newtype[NombreElements];
You can also create and initialize an array at the same time. Example:
1.2 Example
// Cr´eation et initialisation d'un tableau de 4 r´eels
double[]tab={12.0,2.6,0.5,100.11};
2 Practical exercises
Exercise 1
Écrire la classeAnn´eeavec une m´ethode qui permet de d´eterminer si une ann´ee est bissextile
A year is a leap year if we have one of the following two cases:
The year is divisible by 4 and not divisible by 100.
The year is divisible by 400.
Exercise 2
Ẃrite the DayOfWeek class with a method that, given an integer representing a
day of the week (between 1 and 7), display the corresponding name of that day.
Examples:
jour = 1 =>Affichage : ”C’est lundi”
jour = 2 =>Affichage : ”C’est mardi”
Exercise 3
Ẃrite a program that reads 2 arguments which are a positive integer (denoted n) and
a string of characters, then displays this string n times (on different lines).
For example, if the user passes the arguments '5' and 'Hello', we will have the following output
vant:
Hello once
Hello2times
Hello4times
Hello 5 times
Exercise 4
Ẃrite the Perfect class with a method that takes a positive integer and indicates if it is.
is a perfect number or not. A perfect number is equal to the sum of its proper divisors.
(except for himself).
Examples of perfect numbers:
6=1+2+3
28 = 1 + 2 + 4 + 7 + 14
496 = 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248
Exercise 5
Ẃrite a program that calculates and displays the sum of the integers passed as arguments.
Exercise 6
Ćreate the Pair class with 2 methods. The first allows you to fill an array of integers.
The second displays the even elements of an array of integers.
import [Link];
public class Pair{
public void remplirTab(int[] t)
/* fill t with entered integers */
public void displayPair(int[] t)
/* display the even elements of t */
Exercise 7
Ẃrite the class Tabayant with 3 methods. The first one allows you to create an array of integers of
size (to be entered) and to fill it. The second displays the elements of an array of integers.
third returns the largest element of an array of integers.
import [Link];
public class Tab{
public static int[] creationTableau() {
1. Enter the size of the array, creation of the array
2. fill the table from entered integers
3. return this table */
Exercise 8
Ẃrite a program that creates and fills an array of real numbers from the arguments, then
reverse this table and display its elements.
Exercise 9
Ẃrite a program that inputs and fills an array of strings, then inputs
a string and indicate whether this string is in the array. In the case where the string exists,
the program must also display its position in the table.
Note: Use the method [Link](string) to compare between two strings.
Examples:
Exercise 10
Ẃrite a program that allows entering and filling the elements of an array.
of integers, then performs the selection sort in ascending order on this array, and finally displays
the painting.
Principle:
For each element tab[i], determine the index of the smallest element to the right of tab[i].
(smaller than tab[i]), then swap tab[i] and tab[min]. If we do not find an element more
small quetab[i], so no permutation is made.
1 Practical exercises
Exercise 1
We want to model a point in a plane having an orthonormal reference.
´
1. Write the Point class containing the necessary attributes as well as a constructor taking
parameters.
2. Add another constructor without parameters that initializes a point at the position (0,0).
3. For each attribute, add a getter method (get) to return the value of
the attribute, and a mutator method (set) to modify the value of the attribute.
4. Add the method public void modifyCoord(double x, double y) which
allows to modify the coordinates of a point.
´
5. Write the method public boolean samePosition(Point p) that verifies if a point has the
same coordinates as point p.
´
6. Write the method public boolean isSymmetric(Point p) that verifies if a point is
symmetric to point p with respect to the origin of the coordinate system (0,0).
7. Add the method public double distance(Point p) allowing to calculate and
return the distance between a point and point p according to the following formula:
(x−xp )2+ (y−yp )2
p
Use the predefined methods [Link](x, 2) to calculate the square of x and [Link](x)
for the square root of an x.
8. In the same package, create the class TestPoint containing the main method to
test the methods of the class Point:
public class TestPoint
{
public staticvoidmain(String[]args)
{
Point p1=newPoint(5,3);
Point p2=newPoint();
[Link]("p1("+[Link]()+","+[Link]()+")");
[Link]("p2("+[Link]()+","+[Link]()+")");
[Link](5,10);
[Link]("p2("+[Link]()+","+[Link]()+")");
if()
p1 and p2 ndo not have the same position);
Point p3=newPoint(-5,-3);
[Link]("p3("+[Link]()+","+[Link]()+")");
if([Link](p3))
p1 and p3 are symmetric
[Link]("The distance between p1 and p2 is " + [Link](p2));
}
}
Exercise 2
We want to model a date characterized by a day, a month, and a year.
´
1. Write the Date class with the necessary attributes as well as a constructor that
initialize a date.
2. For each attribute, add a getter method (get) to return the value of
the attribute, and a mutator method (set) to modify the value of the attribute.
3. Redefine the method public String toString() that returns a date in the form:
day/month/year
4. Add the method private boolean leapYear() that verifies if the year of a date
is a leap year or not. A year is a leap year in the following cases:
It is divisible by 4 and not by 100.
It is divisible by 400.
5. Add the method private int numberOfDaysInMonth() that returns the number of days
of the month (for example: month = 1 ⇒ number of days = 31). Use the previous method.
´
6. Write the public boolean isValid() method to verify if a date is
correct or not. Use the previous method.
7. Add the public boolean moreRecent(Date d) method that indicates if a date is
more recent than the date of.
8. In the same package, create the TestDate class containing the main method to test.
the methods of the Date class:
public class TestDate
{
public static void main(String[] args)
{
Date d1=new Date(28,2,2018);
if([Link]())
[Link](d1 + " is valid");
Date d2=newDate(30,2,2017);
if(![Link]())
[Link](d2+" nis not valid);
Date d3=new Date(17,10,2020);
if([Link](d1))
[Link](d3 + " is more recent than " + d1);
}
}
Exercise 3
We want to model a stack of integers stored in the form of an array.
1. Define the Stack class with attributes an integer size (the size of the stack), a
another integer named tailleMax (the maximum size of the stack, a constant) and an array
of integers named p.
2. Add a constructor, taking an integer parameter named, which initializes size to zero
set the sizeMax, then create the array with the size sizeMax.
3. Add the accessor method public int getSize() that allows returning the size of
the battery.
´
4. Write the method public boolean isEmpty() that indicates whether the stack is empty or not.
5. Add the method public boolean isFull() that indicates whether the stack is full or not.
6. Add the method public void display() that displays the elements of the stack.
´
7. Write the method public void empiler(int x) that adds x to the end of the stack and increments
Remove 1 if the stack is not full. Display a message if the stack is already full.
´
8. Write the method public void depile() which removes the last element (it is enough to
decrement the size by 1) if the stack is not empty. Display a message if the stack is already
see.
9. In the same package, define the TestPile class with the main method and test it.
methods of the class Stack.
Exercise 4
We want to model a linked list composed of several nodes where each node
contains an integer.
1. Write ´ the Node class with an integer attribute and a reference to the node.
following namedfollowing(nodeType).
2. Add a constructor to the Node class, taking an integer parameter, which initializes val.
to the value of the parameter. The following reference will point to null.
3. Add accessor and mutator methods to the Node class to retrieve
and to modify the attributes of this class.
4. Add, in the same package, the class List with a reference as an attribute on the
tˆete de liste nomm´eetˆete(typeNoeud) et un entiertaillequi est la taille de cette liste.
5. Add a constructor to the List class, without parameters, that initializes the head reference.
.orezotgnilNlu
6. Add accessor and mutator methods to the List class to retrieve the
head and size and modify only the head.
7. Add the method public boolean isEmpty() which indicates whether the list is empty or not.
8. Add the public void display() method that traverses the list and displays the values of
its nodes.
9. Add the method public void addInteger(int val) that adds a node, having the
integer value, at the end of the list and incremented by 1.
´
10. Write the method public void deleteInteger(int val) that deletes the first node
met from the head having the value val, and decrement detailed by 1 if this node has been
found.
11. In the same package, add the TestList class containing the main method with the
following code:
List lst=newList();
[Link](15);
[Link](-9);
[Link](5);
[Link](-26);
[Link](42);
[Link]();
Removing -26 then 15:
[Link](-26);
[Link](15);
[Link]();
Adding 103:
[Link](103);
[Link]();
[Link]("La liste contient "+[Link]()+" noeuds");
Utilization of heritage.
Understand polymorphism.
Understand the usefulness of an abstract class.
Creation and use of a dynamic table.
1 Course concepts
1.1 Creation and manipulation of a dynamic array
To create a resizable array, you can use the ArrayList class:
Import the ArrayList class at the beginning of the file
import [Link];
...
Creation of a dynamic array of String
ArrayList<String>tab=newArrayList<>();
It should be noted that this class does not allow the creation of arrays of primitive types.
To remedy this lack, we can use wrapper classes.
Method Role
add(inti, Objecte) Add the object to the specified index of the array.
remove(inti) Remove the element with the index from the array.
1.4 Example
Import the ArrayList class at the beginning of the file, just after the package.
import [Link];
...
ArrayList<String> tab = new ArrayList<>();
Hello
Hello
[Link](0,"Hello");// adds to the beginning of the array
Goodbye
Thank you
2 practical exercises
Exercise 1
A company wants to manage its employee list with a Java application. There is
mainly two types of employees: managers and workers.
1. Knowing that an employee is described by their identification number, name, age, and salary, define
the Employee class having a constructor with parameters that initializes all its attributes.
2. Add a static integer attribute initialized to 0 and that will be incremented by 1
Each time an employee is created.
3. Add the methods getAge, getSalary and setSalary, as well as the static method
getName
4. Redefine the public method toString that returns the information of an employee according to
this form:
matricule nom,a^ge ans, salaire dt
Example: E10268 Ahmed SASSI, 34 years old, 1200 dt
5. Define, in the same package, the Worker class knowing that a worker has the same
properties of an employee. Add a constructor with parameters that initializes the values
attributes.
6. Define, in the same package, the class Frame knowing that in addition to the properties of a
employee, each executive has a role. Add a constructor with parameters that
initialize the values of the attributes.
7. Redefine the method toString in the Worker class by adding the word 'Worker' to it.
end of the reversed chain. Example:
E10270 Mounir DRIDI,36ans,900dt, Ouvrier
8. Redefine the toString method in the Frame class by adding the frame's function.
the end of the returned chain. Example:
E10268 Ahmed SASSI,34ans,1200dt, Analyste
9. The company has decided to increase the salaries of its employees according to this formula:
For the workers, a raise of 100 dt.
— For the executives:
An increase of 200 dt if the age is below 35 years.
A 300 dt increase if the age is between 35 years and 45 years.
An increase of 400 dt for the others.
Declare the public abstract method increase in the Employee class. Thus, the
class Employee will become abstract, and the method increase must be defined in
the working class and the managerial class.
10. In order to test these classes and their methods, create, in the same package, the class
TestEmployee having the method main with the following code:
Employee[] list = new Employee[5];
liste[0] =newCadre("E10268","Ahmed SASSI",34,1200,"Analyste");
liste[1] =newCadre("E10269","Ridha DRIDI",46,1350,"Comptable");
liste[2] =newOuvrier("E10270","Mounir DRIDI",36,900);
liste[3] =newOuvrier("E10271","Alia ARBI",29,850);
liste[4] =newCadre("E10272","Amal TOUATI",38,1850,"Directeur RH");
Exercise 2
We want to model the concepts of vehicle, car, and airplane.
Define the Vehicle class which has attributes that are valid for any type.
de v´ehicule: son mod`ele, son ann´ee d’achat, son prix d’achat et son prix courant.
2. Add a constructor with 3 parameters (model, year of purchase, and purchase price) that
initialize all these attributes. The current price will be set to the purchase price.
3. Redefine the toString method that returns the information of a vehicle in the specified format.
next:
mod`ele, ann´eeAchat, prixAchat dt, prixCourant dt
//Exemple: Peugeot 206, 2005, 16000 dt, 12000 dt
6. Define, in the same package, the class Aircraft which also inherits from Vehicle and having
the following additional attributes:
number of passengers
flight hours
Add a constructor with parameters that initializes all the attributes. Here too, the
the current price will be set at the purchase price.
7. Redefine the toString method in the Car class by adding the relevant information.
to the car at the end of the returned chain. Example:
PEUGEOT206,2005,20000.0dt,10000.0dt,4portes,5cv,200000km
8. Redefine the method toString in the Airplane class by adding the specific information.
"to the plane" at the end of the returned chain. Example:
CESSNA CITATION II,1982,4000000.0dt,2200000.0dt,9passagers,15300heures
11. In order to test these classes and their methods, create, in the same package, the class
Test vehicle with the following method code:
ArrayList<Vehicle> tab = new ArrayList<>();
1 Practical exercise
We want to implement the following class diagram:
(pReal + pImaginary*i)
(5.2 + 3.6*i)
Complex c1=newComplex(2,3.6);
Complex c2=newComplex(5.1,10.22);
Complex c3 = (Complex)[Link](c2);
[Link](c1 + " + " + c2 + " = " + c3);
Reel r1=newReel(9.0);
Reel r2=newReel(-2.1);
try{
[Link]("The square root of " + r1 + " is " + [Link]());
}
catch(Exception e) {
[Link]([Link]());
}
try{
[Link]("The square root of " + r2 + " is " + [Link]());
}
catch(Exception e) {
[Link]([Link]());
}
Reel r3 = (Reel) [Link](r2);
[Link](r1 + " + " + r2 + " = " + r3);