Académique Documents
Professionnel Documents
Culture Documents
INF1120 – Programmation I
Mélanie Lord
Université du Québec à Montréal
lord.melanie@uqam.ca
INF1120 - Programmation I : Introduction au langage Java
2
INF1120 - Programmation I : Introduction au langage Java
Méthode main
}
}
Les identificateurs
! Pour nommer les variables, constantes, méthodes, classes, objets, etc.
! Formés de lettres, chiffres (sauf au début), _ , $ (non recommandé)
! Lettres accentuées acceptées, mais non recommandées
! Ne doit pas être un mot réservé du langage
! Nbr de caractères illimité, mais le compilateur n’utilise que les 247 premiers.
! Sensibles à la casse : nbHeures est différent de nbheures
3
INF1120 - Programmation I : Introduction au langage Java
Exemples :
Les commentaires
/*
Ceci est un commentaire
sur plusieurs
lignes
*/
/**
* Ceci est un commentaire de documentation (Javadoc)
* @author melanie lord
* @version septembre 2015
*/
4
INF1120 - Programmation I : Introduction au langage Java
5
INF1120 - Programmation I : Introduction au langage Java
6
INF1120 - Programmation I : Introduction au langage Java
Les caractères
Type Nbr Intervalle des valeurs Constante Java des
d’octet(s) valeurs maximum et
minimum
char 2 65536 caractères Unicode Character.MIN_VALUE
(Unicode = 0)
(contrairement à 256 ASCII/ANSI à
sur 1 octet) Character.MAX_VALUE
(Unicode = 65535)
7
INF1120 - Programmation I : Introduction au langage Java
8
INF1120 - Programmation I : Introduction au langage Java
Les booléens
Type Nbr d’octet(s) valeurs Constantes Java
boolean 4 true Boolean.TRUE (= true)
boolean b1 = true;
boolean b2 = !b1; // initialisation par une expression logique
10
INF1120 - Programmation I : Introduction au langage Java
À ne pas faire…
int i;
int j = i; // Erreur de compilation, car i n’est pas initialisé
// ------------
// VARIABLES
// ------------
double nbrHeures; //le nombre d'heures travaillees
double tauxHoraire; //le taux salarial horaire
double salaireHebdo; //le salaire hebdomadaire
}
}
11
INF1120 - Programmation I : Introduction au langage Java
Les constantes
12
INF1120 - Programmation I : Introduction au langage Java
À ne pas faire :
final boolean B = true; // B => const. symb., true => const. litt.
! Par défaut, une constante littérale entière est de type int (ou long si la
valeur est trop grande pour un int). Si c’est un long, il faut utiliser L ou l à la
fin du nombre.
Exemples : int unEntier = 100;
long unEntierLong = 9999999999L; // ok
System.out.println(9999999999l); // ok
long unEntierLong = 9999999999; // err. compilation
13
INF1120 - Programmation I : Introduction au langage Java
! Par défaut, une constante littérale réelle est de type double, mais on peut
la forcer à être un float en ajoutant f ou F.
Exemples :
float montant = 234.56; // ne compile pas
float montant = 234.56F; // ok
float montant = 234.56f; // ok
14
INF1120 - Programmation I : Introduction au langage Java
// ------------
// CONSTANTES
// ------------
final double TAUX_MAX = 17.35;
final double TAUX_MIN = 8.55;
final double NBR_HR_MAX = 80;
final double NBR_HR_MIN = 0;
final double NBR_HR_NORMAL = 40;
final double TEMPS_SUP = 1.5;
final String MSG_SOL_TAUX_HORAIRE = "Entrez le taux horaire : ";
final String MSG_SOL_NBR_HEURES = "Entrez le nombre d’heures "
+ "travaillées : ";
// etc.
}
}
15
INF1120 - Programmation I : Introduction au langage Java
Les opérateurs
Les opérateurs arithmétiques
Opérateurs Signification
- (op. unaire) L’opposée
+ (op. unaire) L’identité
* La multiplication
/ La division (réelle ou entière)
% Le modulo
+ L’addition
- La soustraction
! A priori pour des opérandes de type entier (int ou long) ou réel (float ou
double)
! A priori, les opérandes doivent être du même type.
16
INF1120 - Programmation I : Introduction au langage Java
1. + et - (unaires)
2. *, / et %
3. + et - (binaires)
Exemple :
a - c % d + -3 * b equivaut à a - (c % d) + ((-3) * b)
Dans le cas des réels, aucune opération ne provoque un arrêt de l’exécution. Il existe
des valeurs pour représenter l’infini (positif ou négatif) et une valeur non calculable
(NaN). Les constantes correspondantes sont :
17
INF1120 - Programmation I : Introduction au langage Java
Par exemple :
! La division d’un réel par zéro = Infinity
! Infinity / -Infinity = NaN
! Math.sqrt(-34) = NaN
Conversion implicite
18
INF1120 - Programmation I : Introduction au langage Java
1. Promotion numérique
byte, short et char : convertis en int.
Exemple :
== Égal à
!= Différent de
20
INF1120 - Programmation I : Introduction au langage Java
Exemples :
x - 9 > 7 * y est équivalent à (x - 9) > (7 * y)
a >= b != c < a est équivalent à (a >= b) != (c < a)
Note : les règles de conversion implicite pour les opérateurs arithmétiques s’appliquent aussi
dans le cas d’expressions mixtes contenant des opérateurs relationnels.
& Et
^ Ou exclusif
| Ou (inclusif)
Exemples :
(supposons que a, b, c et d sont des entiers)
a < b && c >= d Si a < b est faux, n’évalue pas le second opérande.
L’opérateur d’affectation
Opérateur Signification
= affectation
Cet opérateur doit, a priori, avoir des opérandes de même type, mais il
existe des règles de conversion implicite très similaires à celles déjà
vues pour le calcul d'une expression.
byte -> short -> int -> long -> float -> double
ou
Exemple :
Affectation de constantes
short n;
n = 45; // Ceci est accepté bien que 45 soit une constante littérale de
// type int.
24
INF1120 - Programmation I : Introduction au langage Java
Exemple : byte i = 0;
i++; //résultat de type byte
25
INF1120 - Programmation I : Introduction au langage Java
Exemples :
int i; char c;
int j; char i;
i = 3; c = 'e';
j = i++; i = ++c;
26
INF1120 - Programmation I : Introduction au langage Java
int n = 999;
byte b = (byte)n // ceci est légal, mais donnera un résultat bizarre. La
// variable b contiendra les 8 bits les moins significatifs
// de n (b contiendra -25, dans ce cas).
double d = 112.89;
int i = (int)d //i contient 112 (la partie décimale est tronquée)
27
INF1120 - Programmation I : Introduction au langage Java
() , ++, --
+ (unaire), - (unaire), !, cast
*, /, %
+, -
<, <=, >, >=
==, !=
&
^
|
&&
||
28
INF1120 - Programmation I : Introduction au langage Java
Promotion numérique
byte, short et char : convertis en int.
Ajustement de type
int -> long -> float -> double
byte -> short -> int -> long -> float -> double
ou
char -> int -> long -> float -> double
29
INF1120 - Programmation I : Introduction au langage Java
Exemples
long k = 3;
int e = 2;
float f = 2.5f;
double d = 5.2;
char c = 'e'; //l'Unicode de 'e' = 101
long g = 5;
boolean b = true;
QUESTIONS:
30
INF1120 - Programmation I : Introduction au langage Java
B) c + 1;
C) (char)c + 1;
D) (char)(c + 1);
31
INF1120 - Programmation I : Introduction au langage Java
Déclaration et initialisation
Exemples :
String s = "toto"; // déclaration et initialisation
String s; // déclaration
…
s = "234"; // initialisation
Note : remarquez que String s’écrit avec un 'S' majuscule contrairement aux
types primitifs.
32
INF1120 - Programmation I : Introduction au langage Java
String s1 = "allo";
String s2 = "toi";
String s3 = s1 + " " + s2; //s3 contient la chaine "allo toi"
String s = "Cinq est plus petit que deux: " + (5 < 2);
33
INF1120 - Programmation I : Introduction au langage Java
Autres exemples
"allo" + 5 + 5 "allo55"
5 + 5 + "allo" "10allo"
56 + "" "56"
"" + 5.3 "5.3"
true + "" "true"
'a' + "" "a"
3 * 2 + "coucou" "6coucou"
"coucou" + 3 * 2 + 7 "coucou67"
5 + "coucou" + 4 / 2 + 7 "5coucou27"
(5 < 3) + "ok" "falseok"
5 < 3 + "ok" NE COMPILE PAS
4 + "allo" + 2 - 7 NE COMPILE PAS
34
INF1120 - Programmation I : Introduction au langage Java
Notions de base
Visibilité des variables : Une variable est visible et existe seulement à l’intérieur
du bloc {…} dans lequel elle a été déclarée.
35
INF1120 - Programmation I : Introduction au langage Java
Instructions
System.out.print (…)
System.out.println (…) ou System.out.println ()
System.out.printf (…)
Instructions
void lireFinLigne()
String lireString()
byte lireByte()
byte lireByteLn()
36
INF1120 - Programmation I : Introduction au langage Java
short lireShort()
short lireShortLn()
int lireInt()
int lireIntLn()
long lireLong()
long lireLongLn()
float lireFloat()
float lireFloatLn()
double lireDouble()
double lireDoubleLn()
char lireChar()
char lireCharLn()
37
INF1120 - Programmation I : Introduction au langage Java
L’instruction if
if (condition) {
bloc_d’instructions_1
}
if (condition) {
bloc_d’instructions_1
} else {
bloc_d’instruction_2
}
38
INF1120 - Programmation I : Introduction au langage Java
if (condition1) {
bloc_d’instructions_1
} else if (condition2) {
bloc_d’instruction_2
} else if (condition3) {
bloc_d’instruction_3
} else {
bloc_d’instruction_4
}
Exemple :
Afficher le jour de la semaine correspondant à un entier de 1 à 7 où 1
représente le dimanche et 7, le samedi.
int jourSemaine;
if (jourSemaine == 1) {
System.out.println("Dimanche");
} else if (jourSemaine == 2) {
System.out.println("Lundi");
} else if (jourSemaine == 3) {
System.out.println("Mardi");
} else if (jourSemaine == 4) {
System.out.println("Mercredi");
} else if (jourSemaine == 5) {
System.out.println("Jeudi");
} else if (jourSemaine == 6) {
System.out.println("Vendredi");
} else if (jourSemaine == 7) {
System.out.println("Samedi");
} else {
System.out.println ("Jour de la semaine invalide.");
}
40
INF1120 - Programmation I : Introduction au langage Java
L’instruction switch
case constante_2:
bloc_instruct_2
//passe à travers
case constante_n:
bloc_instruct_n
break;
41
INF1120 - Programmation I : Introduction au langage Java
Exemples :
switch (2) {
case 2 :
System.out.print(2);
case 3 :
System.out.print(3);
default :
System.out.print("default");
}
//affiche 23default
byte nbr = 2;
switch (nbr) {
case 2 :
System.out.print(2);
case 3 :
System.out.print(3);
break;
default :
System.out.println("default");
}
//affiche 23
42
INF1120 - Programmation I : Introduction au langage Java
switch (s) {
case "Mimi" :
System.out.println("Mimi");
break;
case TOTO :
System.out.println(TOTO);
case "Momo" :
System.out.println("Momo");
break;
default :
System.out.println("default");
}
//affiche Toto
Momo
43
INF1120 - Programmation I : Introduction au langage Java
switch (s) {
case "Mimi" :
System.out.println("Mimi");
break;
case TOTO :
System.out.println(TOTO);
case "Momo" :
System.out.println("Momo");
default :
System.out.println("default");
}
//affiche Momo
default
44
INF1120 - Programmation I : Introduction au langage Java
int jourSemaine;
switch (jourSemaine) {
case 1 :
System.out.println("Dimanche");
break;
case 2 :
System.out.println("Lundi");
break;
case 3 :
System.out.println("Mardi");
break;
case 4 :
System.out.println("Mercredi");
break;
case 5 :
System.out.println("Jeudi");
break;
45
INF1120 - Programmation I : Introduction au langage Java
case 6 :
System.out.println("Vendredi");
break;
case 7 :
System.out.println("Samedi");
break;
default :
System.out.println("Jour de la semaine invalide.");
}
bloc_d’instructions
} while (condition);
46
INF1120 - Programmation I : Introduction au langage Java
Exemples :
Boucle de validation d’un caractère entre ‘a’ et ‘d’ :
char lettre;
do {
System.out.print("Entrez une lettre (a, b, c ou d) : ");
lettre = Clavier.lireCharLn();
47
INF1120 - Programmation I : Introduction au langage Java
do {
if (nbr % 10 == 8) {
trouve = true;
} else {
nbr = nbr / 10;
}
System.out.println(trouve);
Faire trace …
48
INF1120 - Programmation I : Introduction au langage Java
boucle while
while (condition) {
bloc_d’instructions
Exemples :
Boucle de validation d’un caractère entre ‘a’ et ‘d’
char lettre;
49
INF1120 - Programmation I : Introduction au langage Java
if (nbr % 10 == 8) {
trouve = true;
} else {
nbr = nbr / 10;
}
}
System.out.println(trouve);
Faire trace…
50
INF1120 - Programmation I : Introduction au langage Java
boucle for
bloc_d’instructions
Si condition est absente, elle est considérée comme vraie (boucle infinie).
51
INF1120 - Programmation I : Introduction au langage Java
Exemples :
Cas typique :
//affiche : 3 4 5 6 7
Boucles infinies
for ( ; ; ) {
System.out.println("infinie");
}
for (int i = 2 ; ; ) {
System.out.println(i);
}
//n’affiche rien
53
INF1120 - Programmation I : Introduction au langage Java
//affiche : 6, 5, 4, 3,
//affiche : 6
54
INF1120 - Programmation I : Introduction au langage Java
Exemples récapitulatifs
CalculerSalaire.java
o Traduction en Java de l'algorithme en pseudocode
CalculerSalaireAvecConstantesHorsMain.java
o Identique à CalculerSalaire.java, MAIS avec les constantes déclarées au
niveau de la classe plutôt que dans la méthode main.
ProgrammeAvecMenu.java
o Exemple générique d'un programme avec menu pouvant vous servir pour le TP1.
Calculateur.java
o Exemple concret d'un programme avec menu.
55
INF1120 - Programmation I : Introduction au langage Java
56
INF1120 - Programmation I : Introduction au langage Java
Exercices
Voir le fichier IntroJava_ExercicesEtSolutions.pdf
Références
VR DELANNOY, C. Programmer en Java - Java 5 et 6, 6e édition, Eyrolles, 2009.
57