t
t
t
t
t t 3) Contrôle du flux du programme
tttt
3) Contrôle du flux du programme
Texte original t Traducteur : Jean-Pierre VIDAL
t
t
    
Ce chapitre contient 6 pages
1 2 3 4 5 6
\\\
t t t
t t t
t
05.07.01 - version 2.3 [Armel]
- Ajout des tags de séparation de pages pour le site.
15.06.2001 - version 2.2 [J-P Vidal]
- prise en compte des corrections demandées par lsom@...
28.04.2001 - version 2.1 [Armel]
- Remise en forme du code html (titres-hx[verdana], paragraphes-p[Georgia], code-blockquote).
25/06/2000 - version 2.0 [J-P Vidal]
- Dernière mise à jour de la version française.
Traducteur :
- Jean-Pierre VIDAL    
Texte original :
-Thinking in Java, 2nd edition, Revision 10
© 2000 by Bruce Eckel
t t t
3: Controlling Program Flow t 3 : Contrôle du Flux de Programme
t t t
Like a sentient creature, a program must manipulate its world and make choices during execution. t Tout comme une créature sensible, un programme doit agir sur son environnement et faire des choix durant sa vie.
t t t
In Java you manipulate objects and data using operators, and you make choices with execution control statements. Java was inherited from C++, so most of these statements and operators will be familiar to C and C++ programmers. Java has also added some improvements and simplifications. t En Java les objets et les données sont manipulés au moyen d'opérateurs, et les choix sont faits au moyen des instructions de contrôle d'exécution. Java a hérité de C++, c'est pourquoi beaucoup d'instructions seront familières aux programmeurs C et C++. Java a également amené quelques améliorations et aussi quelques simplifications.
t t t
If you find yourself floundering a bit in this chapter, make sure you go through the multimedia CD ROM bound into this book: Thinking in C: Foundations for Java and C++. It contains audio lectures, slides, exercises, and solutions specifically designed to bring you up to speed with the C syntax necessary to learn Java. t Si vous avez l'impression de patauger quelque peu dans ce chapitre, voyez le CD ROM multimédia fourni avec le livre : Thinking in C : Foundations for Java and C++. Il contient des cours audio, des diapositives, des exercices, et des solutions, le tout spécialement conçu pour vous familiariser rapidement avec la syntaxe C nécessaire pour apprendre Java.
t t t

Using Java operators

t

Utilisation des opérateurs Java

t t t
An operator takes one or more arguments and produces a new value. The arguments are in a different form than ordinary method calls, but the effect is the same. You should be reasonably comfortable with the general concept of operators from your previous programming experience. Addition (+), subtraction and unary minus (-), multiplication (*), division (/), and assignment (=) all work much the same in any programming language. t Un opérateur agit sur un ou plusieurs arguments pour produire une nouvelle valeur. Les arguments se présentent sous une forme différente de celle d'un appel de méthode standard, mais le résultat est le même. Votre expérience de programmation antérieure a dû vous familiariser avec les concepts généraux des opérateurs. L'addition (+), la soustraction et le moins unaire (-), la multiplication (*), la division (/), et l'affectation (=) fonctionnent de la même manière dans tous les langages de programmation.
t t t
All operators produce a value from their operands. In addition, an operator can change the value of an operand. This is called a side effect. The most common use for operators that modify their operands is to generate the side effect, but you should keep in mind that the value produced is available for your use just as in operators without side effects. t Tous les opérateurs produisent une valeur à partir de leurs opérandes. En outre, un opérateur peut changer la valeur de l'un de ses opérandes. C'est ce qu'on appelle un effet de bord. L'utilisation la plus fréquente des opérateurs modifiant leurs opérandes est justement de générer un effet de bord, mais dans ce cas il faut garder à l'esprit que la valeur produite est disponible tout comme si on avait utilisé l'opérateur sans chercher à utiliser son effet de bord.
t t t
Almost all operators work only with primitives. The exceptions are ‘=’, ‘==’ and ‘!=’, which work with all objects (and are a point of confusion for objects). In addition, the String class supports ‘+’ and ‘+=’. t Presque tous les opérateurs travaillent uniquement avec les types primitifs. Les exceptions sont « = », « == » et « != », qui fonctionnent avec tous les objets (ce qui est parfois déroutant lorsqu'on traite des objets). De plus, la classe String admet les opérateurs « + » et « += ».
t t t

Precedence

t

Priorité

t t t
Operator precedence defines how an expression evaluates when several operators are present. Java has specific rules that determine the order of evaluation. The easiest one to remember is that multiplication and division happen before addition and subtraction. Programmers often forget the other precedence rules, so you should use parentheses to make the order of evaluation explicit. For example: t La priorité des opérateurs régit la manière d'évaluer une expression comportant plusieurs opérateurs. Java a des règles spécifiques qui déterminent l'ordre d'évaluation. La règle la plus simple est que la multiplication et la division passent avant l'addition et la soustraction. Souvent les programmeurs oublient les autres règles de priorité, aussi vaut-il mieux utiliser les parenthèses afin que l'ordre d'évaluation soit explicite. Par exemple :
t t t
A = X + Y - 2/2 + Z;
t
A = X + Y - 2/2 + Z;
t t t
has a very different meaning from the
same statement with a particular grouping of parentheses:

t a une signification différente de la même instruction dans laquelle certains termes sont groupés entre parenthèses :
t t t
A = X + (Y - 2)/(2 + Z);



t
A = X + (Y - 2)/(2 + Z);
t t t


Assignment


t

L'affectation

t t t
Assignment is performed with the operator
=. It means “take the value of the right-hand side (often called the
rvalue) and copy it into the left-hand side (often
called the lvalue). An rvalue is any constant,
variable or expression that can produce a value, but an lvalue must be a
distinct, named variable. (That is, there must be a physical space to store a
value.) For instance, you can assign a constant value to a variable (A =
4;
), but you cannot assign anything to constant value—it cannot be an
lvalue. (You can’t say 4 = A;.)
t L'affectation est réalisée au moyen de l'opérateur « = ». Elle signifie « prendre la valeur se trouvant du côté droit (souvent appelée rvalue) et la copier du côté gauche (souvent appelée lvalue)  ». Une rvalue représente toute constante, variable ou expression capable de produire une valeur, mais une lvalue doit être une variable distincte et nommée (autrement dit, il existe un emplacement physique pour ranger le résultat). Par exemple, on peut affecter une valeur constante à une variable (A = 4;), mais on ne peut pas affecter quoi que ce soit à une valeur constante - elle ne peut pas être une lvalue (on ne peut pas écrire 4 =A;).
t t t
Assignment of primitives is quite
straightforward. Since the primitive holds the actual value and not a reference
to an object, when you assign primitives you copy the contents from one place to
another. For example, if you say A = B for primitives, then the contents
of B are copied into A. If you then go on to modify A,
B is naturally unaffected by this modification. As a programmer, this is
what you’ve come to expect for most situations.
t L'affectation des types primitifs est très simple. Puisque les données de type primitif contiennent une valeur réelle et non une référence à un objet, en affectant une valeur à une variable de type primitif on copie le contenu d'un endroit à un autre. Par exemple, si on écrit A = B pour des types primitifs, alors le contenu de B est copié dans A. Si alors on modifie A, bien entendu B n'est pas affecté par cette modification. C'est ce qu'on rencontre généralement en programmation.
t t t
When you
assign
objects, however, things change. Whenever you manipulate an object, what
you’re manipulating is the reference, so when you assign “from one
object to another” you’re actually copying a reference from one
place to another. This means that if you say C = D for objects, you end
up with both C and D pointing to the object that, originally, only
D pointed to. The following example will demonstrate this.

t Toutefois, les choses se passent différemment lorsqu'on affecte des objets. Quand on manipule un objet, on manipule en fait sa référence, ce qui fait que lorsqu'on effectue une affectation « depuis un objet vers un autre », en réalité on copie une référence d'un endroit à un autre. En d'autres termes, si on écrit C = D pour des objets, après l'exécution C et D pointeront tous deux vers l'objet qui, à l'origine, était pointé uniquement par D. L'exemple suivant démontre cela.
t t t
Here’s the
example:

t Voici l'exemple :
t t t
//: c03:Assignment.java
// Assignment with objects is a bit tricky.

class Number {
  int i;
}

public class Assignment {
  public static void main(String[] args) {
    Number n1 = new Number();
    Number n2 = new Number();
    n1.i = 9;
    n2.i = 47;
    System.out.println("1: n1.i: " + n1.i +
      ", n2.i: " + n2.i);
    n1 = n2;
    System.out.println("2: n1.i: " + n1.i +
      ", n2.i: " + n2.i);
    n1.i = 27;
    System.out.println("3: n1.i: " + n1.i +
      ", n2.i: " + n2.i);
  }
} ///:~
t
//: c03:Assignment.java
// l'affectation avec des objets n'est pas triviale.

class Number {
  int i;
}

public class Assignment {
  public static void main(String[] args) {
    Number n1 = new Number();
    Number n2 = new Number();
    n1.i = 9;
    n2.i = 47;
    System.out.println("1: n1.i: " + n1.i +
      ", n2.i: " + n2.i);
    n1 = n2;
    System.out.println("2: n1.i: " + n1.i +
      ", n2.i: " + n2.i);
    n1.i = 27;
    System.out.println("3: n1.i: " + n1.i +
      ", n2.i: " + n2.i);
  }
} ///:~
t t t
The Number class is simple, and two instances of it (n1 and n2) are created within main( ). The i value within each Number is given a different value, and then n2 is assigned to n1, and n1 is changed. In many programming languages you would expect n1 and n2 to be independent at all times, but because you’ve assigned a reference here’s the output you’ll see: t La classe Number est simple, main( ) en crée deux instances (n1 etand n2). La valeur i de chaque Number est initialisée différemment, puis n2 est affecté à n1. Dans beaucoup de langages de programmation on s'attendrait à ce que n1 et n2 restent toujours indépendants, mais voici le résultat de ce programme, dû au fait qu'on a affecté une référence :
t t t
1: n1.i: 9, n2.i: 47
2: n1.i: 47, n2.i: 47
3: n1.i: 27, n2.i: 27
t
1: n1.i: 9, n2.i: 47
2: n1.i: 47, n2.i: 47
3: n1.i: 27, n2.i: 27
t t t
Changing the n1 object appears to change the n2 object as well! This is because both n1 and n2 contain the same reference, which is pointing to the same object. (The original reference that was in n1 that pointed to the object holding a value of 9 was overwritten during the assignment and effectively lost; its object will be cleaned up by the garbage collector.) t Si on modifie l'objet n1, l'objet n2 est lui aussi modifié ! Ceci parce que n1 et n2 contiennent une même référence pointant vers le même objet. (la référence originale qui se trouvait dans n1 et qui pointait sur un objet contenant la valeur 9 a été écrasée lors de l'affectation et a été perdue ; l'objet sur lequel elle pointait sera nettoyé par le ramasse-miettes).
t t t
This phenomenon is often called aliasing and it’s a fundamental way that Java works with objects. But what if you don’t want aliasing to occur in this case? You could forego the assignment and say: t Ce phénomène est souvent appelé aliasing (fausse désignation) et c'est la manière fondamentale de gérer les objets en Java. Bien. Et si on ne veut pas de l'aliasing ? Alors il ne faut pas utiliser l'affectation directe n1 = n2, il faut écrire :
t t t
n1.i = n2.i;
t
n1.i = n2.i;
t t t
This retains the two separate objects
instead of tossing one and tying n1 and n2 to the same object, but
you’ll soon realize that manipulating the fields within objects is messy
and goes against good object-oriented design principles. This is a nontrivial
topic, so it is left for Appendix A, which is devoted to aliasing. In the
meantime, you should keep in mind that assignment for objects can add
surprises.
t Les deux objets restent indépendants plutôt que d'en perdre un et de faire pointer n1et n2 vers le même objet ; mais on s'aperçoit très vite que manipuler les champs des objets ne donne pas un code lisible et va à l'encontre des bons principes de la conception orientée objet. C'est un sujet non trivial, je le laisserai de côté et je le traiterai dans l'Annexe A, consacrée à l'aliasing. En attendant, gardons à l'esprit que l'affectation des objets peut entraîner des surprises.
t t t


Aliasing during method calls


t

L'aliasing pendant l'appel des méthodes

t t t
Aliasing will also occur when you pass an
object into a method:

t L'aliasing peut également se produire en passant un objet à une méthode :
t t t
//: c03:PassObject.java
// Passing objects to methods may not be what
// you're used to.

class Letter {
  char c;
}

public class PassObject {
  static void f(Letter y) {
    y.c = 'z';
  }
  public static void main(String[] args) {
    Letter x = new Letter();
    x.c = 'a';
    System.out.println("1: x.c: " + x.c);
    f(x);
    System.out.println("2: x.c: " + x.c);
  }
} ///:~
t
//: c03:PassObject.java
// Le passage d'objets à une méthodes peut avoir
// un effet différent de celui qu'on espère


class Letter {
  char c;
}

public class PassObject {
  static void f(Letter y) {
    y.c = 'z';
  }
  public static void main(String[] args) {
    Letter x = new Letter();
    x.c = 'a';
    System.out.println("1: x.c: " + x.c);
    f(x);
    System.out.println("2: x.c: " + x.c);
  }
} ///:~
t t t
In many programming languages, the method f( ) would appear to be making a copy of its argument Letter y inside the scope of the method. But once again a reference is being passed so the line t Dans beaucoup de langages de programmation, la méthode f( ) est censée faire une copie de son argument Letter y dans la zone de visibilité de la méthode. Mais, encore une fois, c'est une référence qui est passée et donc la ligne :
t t t
y.c = 'z';
t
y.c = 'z';
t t t
is actually changing the object outside
of f( ). The output shows this:

t modifie en réalité l'objet se trouvant au-dehors de f( ). Voici la sortie :
t t t
1: x.c: a
2: x.c: z
t
1: x.c: a
2: x.c: z
t t t
Aliasing and its solution is a complex issue and, although you must wait until Appendix A for all the answers, you should be aware of it at this point so you can watch for pitfalls. t L'aliasing et ses conséquences sont un sujet complexe, toutes les réponses à ces questions seront données dans l'Annexe A, mais il vous faut dès maintenant prendre conscience de son existence afin d'en éviter les pièges.
t t t

Mathematical operators

t

Les opérateurs mathématiques

t t t
The basic mathematical operators are the same as the ones available in most programming languages: addition (+), subtraction (-), division (/), multiplication (*) and modulus (%, which produces the remainder from integer division). Integer division truncates, rather than rounds, the result. t Les opérateurs mathématiques de base sont les mêmes que ceux qu'on trouve dans beaucoup de langages de programmation : l'addition (+), la soustraction (-), la division (/), la multiplication (*) et le modulo (%, le reste de la division entière). La division entière tronque le résultat sans l'arrondir.
t t t
Java also uses a shorthand notation to perform an operation and an assignment at the same time. This is denoted by an operator followed by an equal sign, and is consistent with all the operators in the language (whenever it makes sense). For example, to add 4 to the variable x and assign the result to x, use: x += 4. t Java utilise également une notation abrégée pour effectuer en un seul temps une opération et une affectation. Ceci est compatible avec tous les opérateurs du langage (lorsque cela a un sens), on le note au moyen d'un opérateur suivi d'un signe égal. Par exemple, pour ajouter 4 à la variable x et affecter le résultat à x, on écrit : x += 4.
t t t
This example shows the use of the mathematical operators: t Cet exemple montre l'utilisation des opérateurs mathématiques :
t t t
//: c03:MathOps.java
// Demonstrates the mathematical operators.
import java.util.*;

public class MathOps {
  // Create a shorthand to save typing:
  static void prt(String s) {
    System.out.println(s);
  }
  // shorthand to print a string and an int:
  static void pInt(String s, int i) {
    prt(s + " = " + i);
  }
  // shorthand to print a string and a float:
  static void pFlt(String s, float f) {
    prt(s + " = " + f);
  }
  public static void main(String[] args) {
    // Create a random number generator,
    // seeds with current time by default:
    Random rand = new Random();
    int i, j, k;
    // '%' limits maximum value to 99:
    j = rand.nextInt() % 100;
    k = rand.nextInt() % 100;
    pInt("j",j);  pInt("k",k);
    i = j + k; pInt("j + k", i);
    i = j - k; pInt("j - k", i);
    i = k / j; pInt("k / j", i);
    i = k * j; pInt("k * j", i);
    i = k % j; pInt("k % j", i);
    j %= k; pInt("j %= k", j);
    // Floating-point number tests:
    float u,v,w;  // applies to doubles, too
    v = rand.nextFloat();
    w = rand.nextFloat();
    pFlt("v", v); pFlt("w", w);
    u = v + w; pFlt("v + w", u);
    u = v - w; pFlt("v - w", u);
    u = v * w; pFlt("v * w", u);
    u = v / w; pFlt("v / w", u);
    // the following also works for
    // char, byte, short, int, long,
    // and double:
    u += v; pFlt("u += v", u);
    u -= v; pFlt("u -= v", u);
    u *= v; pFlt("u *= v", u);
    u /= v; pFlt("u /= v", u);
  }
} ///:~
t
//: c03:MathOps.java
// Démonstration des opérateurs mathématiques.
import java.util.*;

public class MathOps {
  // raccourci pour éviter des frappes de caractères :
  static void prt(String s) {
    System.out.println(s);
  }
  // raccourci pour imprimer une chaîne et un entier :
  static void pInt(String s, int i) {
    prt(s + " = " + i);
  }
  // raccourci pour imprimer une chaîne et un nombre en virgule flottante :
  static void pFlt(String s, float f) {
    prt(s + " = " + f);
  }
  public static void main(String[] args) {
    // Crée un générateur de nombres aléatoires,
    // initialisé par défaut avec l'heure actuelle :
    Random rand = new Random();
    int i, j, k;
    // '%' limite la valeur maximale à 99 :
    j = rand.nextInt() % 100;
    k = rand.nextInt() % 100;
    pInt("j",j);  pInt("k",k);
    i = j + k; pInt("j + k", i);
    i = j - k; pInt("j - k", i);
    i = k / j; pInt("k / j", i);
    i = k * j; pInt("k * j", i);
    i = k % j; pInt("k % j", i);
    j %= k; pInt("j %= k", j);
    // tests sur les nombres en virgule flottante :
    float u,v,w;  // s'applique aussi aux nombres en double précision
    v = rand.nextFloat();
    w = rand.nextFloat();
    pFlt("v", v); pFlt("w", w);
    u = v + w; pFlt("v + w", u);
    u = v - w; pFlt("v - w", u);
    u = v * w; pFlt("v * w", u);
    u = v / w; pFlt("v / w", u);
    // ce qui suit fonctionne également avec les types
    // char, byte, short, int, long et double :
    u += v; pFlt("u += v", u);
    u -= v; pFlt("u -= v", u);
    u *= v; pFlt("u *= v", u);
    u /= v; pFlt("u /= v", u);
  }
} ///:~
t t t
The first thing you will see are some shorthand methods for printing: the prt( ) method prints a String, the pInt( ) prints a String followed by an int and the pFlt( ) prints a String followed by a float. Of course, they all ultimately end up using System.out.println( ). t Tout d'abord on remarque quelques méthodes servant de raccourcis pour imprimer : la méthode prt( ) imprime une String, pInt( ) imprime une String suivie d'un int et pFlt( ) imprime une String suivie d'un float. Bien entendu toutes se terminent par un appel à System.out.println( ).
t t t
To generate numbers, the program first creates a Random object. Because no arguments are passed during creation, Java uses the current time as a seed for the random number generator. The program generates a number of different types of random numbers with the Random object simply by calling different methods: nextInt( ), nextLong( ), nextFloat( ) or nextDouble( ). t Pour générer des nombres, le programme crée un objet de type Random. Aucun argument n'étant passé à la création, Java utilise l'heure courante comme semence d'initialisation pour le générateur de nombres aléatoires. Pour générer des nombres de différents types, le programme appelle tout simplement différentes méthodes de l'objet Random : nextInt( ), nextLong( ), nextFloat( ) ou nextDouble( ).
t t t
The modulus operator, when used with the result of the random number generator, limits the result to an upper bound of the operand minus one (99 in this case). t L'opérateur modulo, appliqué au résultat du générateur de nombres aléatoires, limite le résultat à un maximum correspondant à la valeur de l'opérande moins un (dans ce cas, 99).
t t t

Unary minus and plus operators

t

Les opérateurs unaires (à un opérande) moins et plus

t t t
The unary minus (-) and unary plus (+) are the same operators as binary minus and plus. The compiler figures out which use is intended by the way you write the expression. For instance, the statement t Le moins unaire (-) et le plus unaire (+) sont identiques au moins binaire et au plus binaire. Le compilateur les reconnaît par le contexte de l'expression. Par exemple, l'instruction :
t t t
x = -a;
t
x = -a;
t t t
has an obvious meaning. The compiler is
able to figure out:

t a une signification évidente. Le compilateur est capable d'interpréter correctement :
t t t
x = a * -b;
t
x = a * -b;
t t t
but the reader might get confused, so it
is clearer to say:

t mais le lecteur pourrait être déconcerté, aussi est-il plus clair d'écrire :
t t t
x = a * (-b);
t
x = a * (-b);
t t t
The unary minus produces the negative of
the value. Unary plus provides symmetry with unary minus, although it
doesn’t have any
effect.
t Le moins unaire a pour résultat la négation de la valeur. Le plus unaire existe pour des raisons de symétrie, toutefois il n'a aucun effet.
t t t


Auto increment and decrement


t

Incrémentation et décrémentation automatique

t t t
Java, like C, is full of shortcuts.
Shortcuts can make code much easier to type, and either easier or harder to
read.
t Java, tout comme C, possède beaucoup de raccourcis. Les raccourcis autorisent un code plus concis, ce qui le rend plus facile ou difficile à lire suivant les cas.
t t t
Two of the nicer shortcuts are the
increment and decrement operators
(often referred to as the auto-increment and
auto-decrement operators). The decrement operator is
-- and means “decrease by one unit.” The increment operator
is ++ and means “increase by one unit.” If a is an
int, for example, the expression ++a is equivalent to (a = a +
1
). Increment and decrement operators produce the value of the variable as a
result.
t Les deux raccourcis les plus agréables sont les opérateurs d'incrémentation et de décrémentation (souvent cités en tant qu'opérateur d'auto-incrémentation et d'auto-décrémentation). L'opérateur de décrémentation est « -- » et signifie « diminuer d'une unité ». L'opérateur d'incrémentation est « ++ » et signifie « augmenter d'une unité ». Si a est un int, par exemple, l'expression ++a est équivalente à (a = a + 1). Le résultat des opérateurs d'incrémentation et de décrémentation est la variable elle-même.
t t t
There are two versions of each type of
operator, often called the prefix and postfix versions. Pre-increment means the
++ operator appears before the variable or expression, and post-increment
means the ++ operator appears after the variable or expression.
Similarly, pre-decrement means the -- operator appears before the
variable or expression, and post-decrement means the -- operator appears
after the variable or expression. For pre-increment and pre-decrement, (i.e.,
++a or --a), the operation is performed and the value is produced.
For post-increment and post-decrement (i.e. a++ or a--), the value
is produced, then the operation is performed. As an example:

t Il existe deux versions de chaque type d'opérateur, souvent nommées version préfixée et version postfixée. Pour les deux opérateurs, incrémentation et décrémentation, préfixée signifie que l'opérateur (« ++ » ou « -- ») se trouve juste avant la variable ou l'expression, postfixée que l'opérateur se trouve après la variable ou l'expression. Pour la pré-incrémentation et la pré-décrémentation, (c'est à dire, ++a ou --a), l'opération est réalisée en premier, puis la valeur est produite. Pour la post-incrémentation et la post-décrémentation (c'est à dire a++ ou a--), la valeur est produite, puis l'opération est réalisée. En voici un exemple :
t t t
//: c03:AutoInc.java
// Demonstrates the ++ and -- operators.

public class AutoInc {
  public static void main(String[] args) {
    int i = 1;
    prt("i : " + i);
    prt("++i : " + ++i); // Pre-increment
    prt("i++ : " + i++); // Post-increment
    prt("i : " + i);
    prt("--i : " + --i); // Pre-decrement
    prt("i-- : " + i--); // Post-decrement
    prt("i : " + i);
  }
  static void prt(String s) {
    System.out.println(s);
  }
} ///:~
t
//: c03:AutoInc.java
// Démonstration des opérateurs ++ et --.

public class AutoInc {
  public static void main(String[] args) {
    int i = 1;
    prt("i : " + i);
    prt("++i : " + ++i); // Pré-incrémentation
    prt("i++ : " + i++); // Post-incrémentation
    prt("i : " + i);
    prt("--i : " + --i); // Pré-décrémentation
    prt("i-- : " + i--); // Post-décrémentation
    prt("i : " + i);
  }
  static void prt(String s) {
    System.out.println(s);
  }
} ///:~
t t t
The output for this program is: t Voici le résultat de ce programme :
t t t
i : 1
++i : 2
i++ : 2
i : 3
--i : 2
i-- : 2
i : 1
t
i : 1
++i : 2
i++ : 2
i : 3
--i : 2
i-- : 2
i : 1
t t t
You can see that for the prefix form you get the value after the operation has been performed, but with the postfix form you get the value before the operation is performed. These are the only operators (other than those involving assignment) that have side effects. (That is, they change the operand rather than using just its value.) t On constate qu'avec la forme préfixée on obtient la valeur de la variable après que l'opération ait été exécutée, et qu'avec la forme postfixée on obtient la valeur de la variable avant que l'opération ne soit réalisée. Ce sont les seuls opérateurs ayant des effets de bord, mis à part ceux qui impliquent l'affectation : en d'autres termes, ils modifient l'opérande au lieu de simplement utiliser sa valeur.
t t t
The increment operator is one explanation for the name C++, implying “one step beyond C.” In an early Java speech, Bill Joy (one of the creators), said that “Java=C++--” (C plus plus minus minus), suggesting that Java is C++ with the unnecessary hard parts removed and therefore a much simpler language. As you progress in this book you’ll see that many parts are simpler, and yet Java isn’t that much easier than C++. t L'opérateur d'incrémentation explique le nom C++, qui voudrait signifier « un pas de plus au-delà de C ». Dans un ancien discours sur Java, Bill Joy (l'un des créateurs), disait que « Java = C++-- » (C plus plus moins moins), suggérant que Java serait C++ auquel on aurait ôté les parties difficiles et non nécessaires, et qu'il serait donc un langage bien plus simple. Au fil de votre lecture, vous découvrirez ici que beaucoup de choses sont plus simples, bien que Java ne soit pas tellement plus simple que C++.
t t t

Relational operators

t

Les opérateurs relationnels

t t t
Relational operators generate a boolean result. They evaluate the relationship between the values of the operands. A relational expression produces true if the relationship is true, and false if the relationship is untrue. The relational operators are less than (<), greater than (>), less than or equal to (<=), greater than or equal to (>=), equivalent (==) and not equivalent (!=). Equivalence and nonequivalence works with all built-in data types, but the other comparisons won’t work with type boolean. t Les opérateurs relationnels créent un résultat de type boolean. Ils évaluent les rapports entre les valeurs des opérandes. Une expression relationnelle renvoie true si le rapport est vrai, false dans le cas opposé. Les opérateurs relationnels sont : plus petit que (<), plus grand que (>), plus petit que ou égal à (<=), plus grand que ou égal à (>=), équivalent (==) et non équivalent (!=). Le type boolean n'accepte comme opérateur relationnel que les opérateurs d'équivalence (==) et de non équivalence (!=), lesquels peuvent être utilisés avec tous les types de données disponibles dans le langage.
t t t

Testing object equivalence

t

Tester l'équivalence des objets

t t t
The relational operators == and != also work with all objects, but their meaning often confuses the first-time Java programmer. Here’s an example: t Les opérateurs relationnels == et != fonctionnent avec tous les objets, mais leur utilisation déroute souvent le programmeur Java novice. Voici un exemple :
t t t
//: c03:Equivalence.java

public class Equivalence {
  public static void main(String[] args) {
    Integer n1 = new Integer(47);
    Integer n2 = new Integer(47);
    System.out.println(n1 == n2);
    System.out.println(n1 != n2);
  }
} ///:~
t
//: c03:Equivalence.java

public class Equivalence {
  public static void main(String[] args) {
    Integer n1 = new Integer(47);
    Integer n2 = new Integer(47);
    System.out.println(n1 == n2);
    System.out.println(n1 != n2);
  }
} ///:~
t t t
The expression System.out.println(n1 == n2) will print the result of the boolean comparison within it. Surely the output should be true and then false, since both Integer objects are the same. But while the contents of the objects are the same, the references are not the same and the operators == and != compare object references. So the output is actually false and then true. Naturally, this surprises people at first. t L'expression System.out.println(n1 == n2) imprimera le résultat de la comparaison de type boolean. Il semble à priori évident que la sortie sera true puis false, puisque les deux objets de type Integer sont identiques. Mais, bien que le contenu des objets soit le même, les références sont différentes, et il se trouve que les opérateurs == and != comparent des références d'objet. En réalité la sortie sera false puis true. Naturellement, cela en surprendra plus d'un.
t t t
What if you want to compare the actual contents of an object for equivalence? You must use the special method equals( ) that exists for all objects (not primitives, which work fine with == and !=). Here’s how it’s used: t Que faire si on veut comparer le contenu réel d'un objet ? Il faut utiliser la méthode spéciale equals( ) qui existe pour tous les objets (mais non pour les types primitifs, qui s'accommodent mieux de == et !=). Voici comment l'utiliser :
t t t
//: c03:EqualsMethod.java

public class EqualsMethod {
  public static void main(String[] args) {
    Integer n1 = new Integer(47);
    Integer n2 = new Integer(47);
    System.out.println(n1.equals(n2));
  }
} ///:~
t
//: c03:EqualsMethod.java

public class EqualsMethod {
  public static void main(String[] args) {
    Integer n1 = new Integer(47);
    Integer n2 = new Integer(47);
    System.out.println(n1.equals(n2));
  }
} ///:~
t t t
t t t
t t
    
///
t t t
t
     
Sommaire Le site de Bruce Eckel