Académique Documents
Professionnel Documents
Culture Documents
Introduction
Programmation Orientée Objet
JAVA
cthiam@univ-thies.sn
1
P.O.O
Langage Java
1) Introduction (rappel)
2
Organisation
• 8 cours
– Mercredi 8h30-12h30
– semaine
• 12 TDM
– groupe 1 (Mercredi xh-yh)
– groupe 2 (Mercredi xh-yh)
– semaine
• Évaluation
– Contrôle continu (amphi+TDM+partiel) (33%)
– Examen (67%)
– ECTS :
3
Bibliographie
4
Quelques sites
Sun
http://java.sun.com
produits, documentation, the JavaTM Tutorial
Java Developer Connection
Gamelan
http://www.gamelan.com
JavaWorld Magazine
http://www.javaworld.com/
Java FAQ
http://www.ibiblio.org/javafaq/javafaq.html 5
Créer votre première application
Le premier programme, Hello, affiche simplement le texte "Hello !"
6
Compilation vs. Interprétation
Programme source
Compilateur
Programme exécutable
Système d’exploitation
Matériel
7
Write once, run anywhere
• La compilation d'un programme, ne génère pas
d'instructions spécifiques à votre plate-forme
8
9
Application "Hello"
Créer le fichier source Java Hello.java
/**
* La classe Hello implémente une
* application qui affiche "Hello !" sur la
* sortie standard
*/
class Hello {
public static void main(String[] args) {
System.out.println("Hello !");
//Affiche le texte
}
}
10
• Compiler le fichier source
javac Hello.java
13
Insérer des commentaires
/**
* Documentation
* ignorer par le compilateur
* générée par l'outil javadoc
*/
class Hello {
public static void main(String[] args) {
System.out.println("Hello !");
// commentaire sur une ligne
/* commentaire … */
}
}
14
Définir une classe
/**
* documentation
*/
class Hello {
public static void main(String[] args) {
System.out.println("Hello !");
// afficher le texte
}
}
class Hello {
public static void main(String[] args) {
System.out.println("Hello !");
// afficher le texte
}
}
System.out.println("Hello !")
La classe System (package java.lang) fournie des accès "system-independent" à
des fonctionnalités "system-dependent"
System.out.println("Hello !")
Variable out de la classe System
System.out.println("Hello !")
Méthode println(…)
17
http://java.sun.com/j2se/1.4.2/docs/api/index.html
18
19
Conventions d’écriture de code
• Classe CompteEnBanque
• Méthodes
– crediterCompte(25)
– getSolde()
– setSolde(10)
• Variables
– empruntCourant
• Constantes
– TAUX_INTERET
20
P.O.O
Langage Java
1) Introduction (rappel)
21
Bases du Langage
public class BasicsDemo {
public static void main(String[] args) {
int sum = 0;
for (int c = 1; c <= 10; c++){sum += c;}
S.o.p("Sum = " + sum);
}
}
22
Concept de Variable
Définition : un élément d’information identifié par un nom
(other types)
char A single character 16-bit Unicode character
A boolean value
boolean
(true or false) true or false
27
Types élémentaires
Integer Floating
Textual Logical
28
Variable Final
• La valeur d’une variable déclarée final ne peut pas
être modifiée après avoir été initialisée
29
Opérateur Arithmétique
30
Opérateur Relationnel
31
Opérateur Conditionnel
Operator Use Returns true if
&& op1 && op2 op1 and op2 are both true
conditionally evaluates op2
|| op1 || op2 either op1 or op2 is true
conditionally evaluates op2
! ! op op is false
& op1 & op2 op1 and op2 are both true
always evaluates op1 and op2
| op1 | op2 either op1 or op2 is true
always evaluates op1 and op2
^ op1 ^ op2 if op1 and op2 are different
that is if one or the other of the
32
operands is true but not both
Entrées au clavier : classe Console
Console.readDouble(str)
• retourne un nombre de type double entré au clavier
33
Utiliser la classe Console
34
Classe Console
Exemples
import unsa.Console;
public class TestConsole{
public static void main (String args[]){
char c = Console.readChar("Entrez un char");
S.o.p("echo: " + c );
int i = Console.readInt("Entrez un int");
S.o.p("echo: " + i );
double d = Console.readDouble("Entrez un double");
S.o.p("echo: " + d );
long l = Console.readLong("Entrez un long");
S.o.p("echo: " + l );
System.exit(0);
}
}
35
Contrôle du Flux d’instructions
36
Les Instructions de Contrôle
if
return
switch
while do-while continue
for
break
37
Instruction while
On utilise l'instruction while pour exécuter répétitivement
un bloc de code tant qu'une condition reste vraie
40
Instruction do-while (2)
String copyFromMe = "Copy this string until you
encounter the letter 'g'.";
StringBuffer copyToMe = new StringBuffer();
int i=0;
char c ;
do {
c = copyFromMe.charAt(i);
copyToMe.append(c);
i=i+1 ;
}
while (c != 'g');
S.o.p(copyToMe);
42
Instruction for
43
for vs. while
for(int i=0 ; i<arrayOfInts.length ; i++)
{
S.o.p(arrayOfInts[i] + " ");
}
int i=0 ;
while(i<arrayOfInts.length)
{
S.o.p(arrayOfInts[i] + " ");
i++;
}
44
Garantir la fin des itérations
do { do {
afficher(a)
afficher(a)
a = a+1;
} }
while (a != 10) while (a != 10)
a = 1; a = 10;
do { do {
afficher(a) afficher(a)
a = a+1 ; a = a+1;
} }
while (a != 10) while (a != 10)
45
Instructions if/else
if (reponse == OK) {
// code to perform OK action
}
if (reponse == OK) {
// code to perform OK action
}
else {
// code to perform Cancel action
}
46
Une cascade de if …
int score = 76;
char grade;
if (score >= 90) { grade = 'A'; }
else // score < 90
if (score >= 80) { grade = 'B'; }
else // score < 80
if (score >= 70) { grade = 'C'; }
else // score < 70
if (score >= 60) { grade = 'D'; }
else // score < 60
{ grade = 'F'; }
char rep ;
rep=Character.toLowerCase(Console.readChar("votre choix ?"));
S.o.p(rep);
53
Capitaliser un texte
Public static void main(String[] args) {
String str=Console.readLine("Tapez un texte");
char ch; // un caractère de str
char prevCh='.'; // le caractère précédent ch
for (int i = 0; i < str.length(); i++ ) {
ch = str.charAt(i);
if ( Character.isLetter(ch) &&
! Character.isLetter(prevCh) )
S.o.p( Character.toUpperCase(ch) );
else S.o.p(ch);
prevCh = ch;
}
}
54
Algorithme d'Euclide
Calculer le PGCD de deux entiers A et B
PGCD(A,B) = PGCD(B,R)
A = (B x Q) + R 0 <= R < B
294 = (231 x 1) + 63
231 = (63 x 3) + 42
63 = (42 x 1) + 21
42 = (21 x 2) + 0
PGCD(294,231) = 21
55
Algorithme d'Euclide
int a=21, b=14 ;
int r ;
S.o.p("PGCD "+a+" et "+b);
r=a%b;
/* division euclidienne de a par b
a=b*q+r et 0<=r<b */
while (r!=0){
a=b ; b=r; // pgcd(a,b)=pgcd(b,r)
r=a%b;
}
S.o.p(b);
56
Le nombre Mystérieux
public static void main (String args[]){
int inconnu = (int) (Math.random()*100);
int score=0;
int prop=Console.readInt("proposition :");
score++;
while (prop != inconnu){
if (prop < inconnu)
S.o.p("TROP PETIT");
else S.o.p("TROP GRAND");
prop=Console.readInt("proposition :");
score++;
}
S.o.p("Vous avez trouvé en "+score+" coups");
System.exit(0);
} 57
Ésoperesteicietserepose
public static void main(String [] args) {
final int taille ;
String phrase=Console.readLine("Entrez une string");
taille = phrase.length();
int i = 0, j = taille - 1;
while(i<taille/2 &&
phrase.charAt(i) == phrase.charAt(j))
{i++ ; j-- ;}
if (I >= taille/2)
S.o.p(phrase+" est un palindrome");
else
S.o.p (phrase+" n’est pas un palindrome");
System.exit(0);
}
58
Ésoperesteicietserepose
b i r
i r
b i r
62
Algorithme du drapeau tricolore
int d[]={3,1,3,1,2,3,2,3,2,1};
// 1=bleu 2=blanc 3=rouge
for(int k=0 ; k<d.length ; k++) { S.o.p(d[k]+" ");}
63
Comment les arguments sont-ils passés aux
méthodes ?
public class CallDemo {
static void f(int b) {
b = 10;
}
public static void main(String [] args) {
int a = 5;
f(a);
S.o.p("a = " + a);
}
}
67
Sales tax in New York City is 8.25%
public static void main (String[] args) {
final double TAUX = 0.0825 ;
double prix=Double.valueOf(args[0]).doubleValue();
//double prix = Double.parseDouble(args[0]);
S.o.p("taxe : " + prix*TAUX);
S.o.p("prix ttc : " + prix*(1+TAUX));
}
code.java
Compilateur JAVA
code.class
JVM JVM
JVM
MAC Unix
Windows
70