t
t
t
t
t t   3) Contrôle du flux du programme
tttt
t
carrea) Préface carreb) Avant-propos carre1) Introduction sur les &laqo; objets » carre2) Tout est &laqo; objet » 3) Contrôle du flux du programme carre4) Initialization & Cleanup carre5) Cacher l'implémentation carre6) Réutiliser les classes carre7) Polymorphisme carre8) Interfaces & classes internes carre9) Stockage des objets carre10) Error Handling with Exceptions carre11) Le système d’E/S de Java carre12) Identification dynamique de type carre13) Création de fenêtres & d'Applets carre14) Les &laqo; Threads » multiples carre15) Informatique distribuée carreA) Passage et retour d'objets carreB) L'Interface Java Natif (JNI) carreC) Conseils pour une programation stylée en Java carreD) Resources
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
t t t
The result will be true, as you would expect. Ah, but it’s not as simple as that. If you create your own class, like this:
t Le résultat sera true, comme on le souhaitait. Mais ce serait trop facile. Si on crée une classe, comme ceci :
t t t
//: c03:EqualsMethod2.java class Value { int i; } public class EqualsMethod2 { public static void main(String[] args) { Value v1 = new Value(); Value v2 = new Value(); v1.i = v2.i = 100; System.out.println(v1.equals(v2)); } } ///:~ t
//: c03:EqualsMethod2.java

class Value {
  int i;
}

public class EqualsMethod2 {
  public static void main(String[] args) {
    Value v1 = new Value();
    Value v2 = new Value();
    v1.i = v2.i = 100;
    System.out.println(v1.equals(v2));
  }
} ///:~
t t t
you’re back to square one: the result is false. This is because the default behavior of equals( ) is to compare references. So unless you override equals( ) in your new class you won’t get the desired behavior. Unfortunately, you won’t learn about overriding until Chapter 7, but being aware of the way equals( ) behaves might save you some grief in the meantime.
t nous voici revenus à la case départ : le résultat est false. Ceci parce que, par défaut, equals( ) compare des références. Aussi, faute de redéfinir equals( ) dans la nouvelle classe, nous n'obtiendrons pas le résultat désiré. Mais la redéfinition des méthodes ne sera exposée que dans le Chapitre 7, aussi d'ici là il nous faudra garder à l'esprit que l'utilisation de equals( ) peut poser des problèmes.
t t t
Most of the Java library classes implement equals( ) so that it compares the contents of objects instead of their references.
t Beaucoup de classes des bibliothèques Java implémentent la méthode equals( ) afin de comparer le contenu des objets plutôt que leurs références.
t t t

Logical operators

t

Les opérateurs logiques

t t t
The logical operators AND (&&), OR (||) and NOT (!) produce a boolean value of true or false based on the logical relationship of its arguments. This example uses the relational and logical operators:
t Les opérateurs logiques AND (&&), OR (||) et NOT (!) produisent une valeur boolean qui prend la valeur true ou false en fonction des arguments. Cet exemple utilise les opérateurs relationnels et logiques :
t t t
//: c03:Bool.java // Relational and logical operators. import java.util.*; public class Bool { public static void main(String[] args) { Random rand = new Random(); int i = rand.nextInt() % 100; int j = rand.nextInt() % 100; prt("i = " + i); prt("j = " + j); prt("i > j is " + (i > j)); prt("i < j is " + (i < j)); prt("i >= j is " + (i >= j)); prt("i <= j is " + (i <= j)); prt("i == j is " + (i == j)); prt("i != j is " + (i != j)); // Treating an int as a boolean is // not legal Java //! prt("i && j is " + (i && j)); //! prt("i || j is " + (i || j)); //! prt("!i is " + !i); prt("(i < 10) && (j < 10) is " + ((i < 10) && (j < 10)) ); prt("(i < 10) || (j < 10) is " + ((i < 10) || (j < 10)) ); } static void prt(String s) { System.out.println(s); } } ///:~ t
//: c03:Bool.java
// Opérateurs relationnels et logiques.
import java.util.*;

public class Bool {
  public static void main(String[] args) {
    Random rand = new Random();
    int i = rand.nextInt() % 100;
    int j = rand.nextInt() % 100;
    prt("i = " + i);
    prt("j = " + j);
    prt("i > j is " + (i > j));
    prt("i < j is " + (i < j));
    prt("i >= j is " + (i >= j));
    prt("i <= j is " + (i <= j));
    prt("i == j is " + (i == j));
    prt("i != j is " + (i != j));

    // Traiter un int comme un boolean
    // n'est pas légal en Java
//! prt("i && j is " + (i && j));
//! prt("i || j is " + (i || j));
//! prt("!i is " + !i);

    prt("(i < 10) && (j < 10) is "
       + ((i < 10) && (j < 10)) );
    prt("(i < 10) || (j < 10) is "
       + ((i < 10) || (j < 10)) );
  }
  static void prt(String s) {
    System.out.println(s);
  }
} ///:~
t t t
You can apply AND, OR, or NOT to boolean values only. You can’t use a non-boolean as if it were a boolean in a logical expression as you can in C and C++. You can see the failed attempts at doing this commented out with a //! comment marker. The subsequent expressions, however, produce boolean values using relational comparisons, then use logical operations on the results.
t On ne peut appliquer AND, OR, et NOT qu'aux valeurs boolean. On ne peut pas utiliser une variable non booléenne comme si elle était booléenne, comme on le fait en C et C++. Les tentatives (erronées) de le faire ont été mises en commentaires avec le marqueur //!. Les expressions qui suivent, toutefois, produisent des valeurs boolean en utilisant les opérateurs de comparaisons relationnels, puis appliquent des opérations logiques sur les résultats.
t t t
One output listing looked like this:
t Exemple de listing de sortie :
t t t
i = 85 j = 4 i > j is true i < j is false i >= j is true i <= j is false i == j is false i != j is true (i < 10) && (j < 10) is false (i < 10) || (j < 10) is true t
i = 85
j = 4
i > j is true
i < j is false
i >= j is true
i <= j is false
i == j is false
i != j is true
(i < 10) && (j < 10) is false
(i < 10) || (j < 10) is true
t t t
Note that a boolean value is automatically converted to an appropriate text form if it’s used where a String is expected.
t Notez qu'une valeur boolean est automatiquement convertie en texte approprié lorsqu'elle est utilisée dans un contexte où on attend une String.
t t t
You can replace the definition for int in the above program with any other primitive data type except boolean. Be aware, however, that the comparison of floating-point numbers is very strict. A number that is the tiniest fraction different from another number is still “not equal.” A number that is the tiniest bit above zero is still nonzero.
t Dans le programme précédent, on peut remplacer la définition int par n'importe quelle autre donnée de type primitif excepté boolean. Toutefois il faut rester attentif au fait que la comparaison de nombres en virgule flottante est très stricte. Un nombre qui diffère très légèrement d'un autre est toujours « différent ». Un nombre représenté par le plus petit bit significatif au-dessus de zéro est différent de zéro.
t t t

Short-circuiting

t

« Court-circuit  »

t t t
When dealing with logical operators you run into a phenomenon called “short circuiting.” This means that the expression will be evaluated only until the truth or falsehood of the entire expression can be unambiguously determined. As a result, all the parts of a logical expression might not be evaluated. Here’s an example that demonstrates short-circuiting:
t En travaillant avec les opérateurs logiques on rencontre un comportement appelé « court-circuit ». Cela signifie que l'évaluation de l'expression sera poursuivie jusqu'à ce que la vérité ou la fausseté de l'expression soit déterminée sans ambiguïté. En conséquence, certaines parties d'une expression logique peuvent ne pas être évaluées. Voici un exemple montrant une évaluation « court-circuitée » :
t t t
//: c03:ShortCircuit.java // Demonstrates short-circuiting behavior. // with logical operators. public class ShortCircuit { static boolean test1(int val) { System.out.println("test1(" + val + ")"); System.out.println("result: " + (val < 1)); return val < 1; } static boolean test2(int val) { System.out.println("test2(" + val + ")"); System.out.println("result: " + (val < 2)); return val < 2; } static boolean test3(int val) { System.out.println("test3(" + val + ")"); System.out.println("result: " + (val < 3)); return val < 3; } public static void main(String[] args) { if(test1(0) && test2(2) && test3(2)) System.out.println("expression is true"); else System.out.println("expression is false"); } } ///:~ t
//: c03:ShortCircuit.java
// Démonstration du fonctionnement du "court-circuit"
// avec les opérateurs logiques.

public class ShortCircuit {
  static boolean test1(int val) {
    System.out.println("test1(" + val + ")");
    System.out.println("result: " + (val < 1));
    return val < 1;
  }
  static boolean test2(int val) {
    System.out.println("test2(" + val + ")");
    System.out.println("result: " + (val < 2));
    return val < 2;
  }
  static boolean test3(int val) {
    System.out.println("test3(" + val + ")");
    System.out.println("result: " + (val < 3));
    return val < 3;
  }
  public static void main(String[] args) {
    if(test1(0) && test2(2) && test3(2))
      System.out.println("expression is true");
    else
      System.out.println("expression is false");
  }
} ///:~
t t t
Each test performs a comparison against the argument and returns true or false. It also prints information to show you that it’s being called. The tests are used in the expression:
t Chaque fonction test effectue une comparaison sur l'argument et renvoie true ou false. De plus elle imprime cette valeur pour montrer qu'elle est appelée. Les tests sont utilisés dans l'expression :
t t t
if(test1(0) && test2(2) && test3(2)) t
if(test1(0) && test2(2) && test3(2))
t t t
You might naturally think that all three tests would be executed, but the output shows otherwise:
t On pourrait naturellement penser que les trois tests sont exécutés, mais la sortie montre le contraire :
t t t
test1(0) result: true test2(2) result: false expression is false t
test1(0)
result: true
test2(2)
result: false
expression is false
t t t
The first test produced a true result, so the expression evaluation continues. However, the second test produced a false result. Since this means that the whole expression must be false, why continue evaluating the rest of the expression? It could be expensive. The reason for short-circuiting, in fact, is precisely that; you can get a potential performance increase if all the parts of a logical expression do not need to be evaluated.
t Le premier test produit un résultat true, et l'évaluation de l'expression se poursuit. Toutefois, le second test produit un résultat false. Puisque cela signifie que l'expression complète sera false, pourquoi poursuivre l'évaluation du reste de l'expression ? Cela pourrait avoir un coût. C'est de fait la justification du « court-circuit » : gagner potentiellement en performance s'il n'est pas nécessaire d'évaluer complètement l'expression logique.
t t t

Bitwise operators

t

Les opérateurs bit à bit

t t t
The bitwise operators allow you to manipulate individual bits in an integral primitive data type. Bitwise operators perform boolean algebra on the corresponding bits in the two arguments to produce the result.
t Les opérateurs bit à bit permettent de manipuler les bits individuels d'une donnée de type primitif. Les opérateurs bit à bit effectuent des opérations d'algèbre booléenne sur les bits en correspondance dans les deux arguments afin de produire un résultat.
t t t
The bitwise operators come from C’s low-level orientation; you were often manipulating hardware directly and had to set the bits in hardware registers. Java was originally designed to be embedded in TV set-top boxes, so this low-level orientation still made sense. However, you probably won’t use the bitwise operators much.
t L'origine des opérateurs bit à bit est à rechercher dans l'orientation bas niveau du langage C ; il fallait alors manipuler directement le hardware ainsi que les bits des registres hardware. Java a été conçu à l'origine pour être embarqué dans les décodeurs TV, ce qui explique cette orientation bas niveau. Vous n'utiliserez vraisemblablement pas beaucoup ces opérateurs.
t t t
The bitwise AND operator (&) produces a one in the output bit if both input bits are one; otherwise it produces a zero. The bitwise OR operator (|) produces a one in the output bit if either input bit is a one and produces a zero only if both input bits are zero. The bitwise EXCLUSIVE OR, or XOR (^), produces a one in the output bit if one or the other input bit is a one, but not both. The bitwise NOT (~, also called the ones complement operator) is a unary operator; it takes only one argument. (All other bitwise operators are binary operators.) Bitwise NOT produces the opposite of the input bit—a one if the input bit is zero, a zero if the input bit is one.
t L'opérateur AND (&) bit à bit retourne la valeur un si les deux bits correspondants des opérandes d'entrée sont à un ; sinon il retourne la valeur zéro. L'opérateur OR (|) bit à bit retourne la valeur un si l'un des deux bits correspondants des opérandes d'entrée est à un et retourne la valeur zéro dans le cas où les deux bits sont à zéro. L'opérateur EXCLUSIVE OR, ou XOR (^), retourne la valeur un si l'un des deux bits correspondants des opérandes est à un, mais pas les deux. L'opérateur NOT bit à bit (~ , appelé également opérateur de complément à un) est un opérateur unaire, il a un seul argument (tous les autres opérateurs bit à bit sont des opérateurs binaires), il renvoie l'opposé de l'argument - un si le bit de l'argument est à zéro, zéro si le bit est à un.
t t t
The bitwise operators and logical operators use the same characters, so it is helpful to have a mnemonic device to help you remember the meanings: since bits are “small,” there is only one character in the bitwise operators.
t Les opérateurs bit à bit et les opérateurs logiques étant représentés par les mêmes caractères, je vous propose un procédé mnémotechnique pour vous souvenir de leur signification : les bits étant « petits », les opérateurs bit à bit comportent un seul caractère.
t t t
Bitwise operators can be combined with the = sign to unite the operation and assignment: &=, |= and ^= are all legitimate. (Since ~ is a unary operator it cannot be combined with the = sign.)
t Les opérateurs bit à bit peuvent être combinés avec le signe = pour réaliser en une seule fois opération et affectation : &=, |= et ^= sont tous légitimes. (~ étant un opérateur unaire, il ne peut être combiné avec le signe =).
t t t
The boolean type is treated as a one-bit value so it is somewhat different. You can perform a bitwise AND, OR and XOR, but you can’t perform a bitwise NOT (presumably to prevent confusion with the logical NOT). For booleans the bitwise operators have the same effect as the logical operators except that they do not short circuit. Also, bitwise operations on booleans include an XOR logical operator that is not included under the list of “logical” operators. You’re prevented from using booleans in shift expressions, which is described next.
t Le type boolean est traité comme une valeur binaire et il est quelque peu différent. Il est possible de réaliser des opérations AND, OR et XOR « bit à bit », mais il est interdit d'effectuer un NOT « bit à bit » (vraisemblablement pour ne pas faire de confusion avec le NOT logique). Pour le type boolean les opérateurs bit à bit ont le même effet que les opérateurs logiques, sauf qu'il n'y a pas de « court-circuit ». De plus, parmi les opérations bit à bit effectuées sur des types boolean il existe un opérateur XOR logique qui ne fait pas partie de la liste des opérateurs « logiques ». Enfin, le type boolean ne doit pas être utilisé dans les expressions de décalage décrites ci-après.
t t t

Shift operators

t

Les opérateurs de décalage

t t t
The shift operators also manipulate bits. They can be used solely with primitive, integral types. The left-shift operator (<<) produces the operand to the left of the operator shifted to the left by the number of bits specified after the operator (inserting zeroes at the lower-order bits). The signed right-shift operator (>>) produces the operand to the left of the operator shifted to the right by the number of bits specified after the operator. The signed right shift >> uses sign extension: if the value is positive, zeroes are inserted at the higher-order bits; if the value is negative, ones are inserted at the higher-order bits. Java has also added the unsigned right shift >>>, which uses zero extension: regardless of the sign, zeroes are inserted at the higher-order bits. This operator does not exist in C or C++.
t Les opérateurs de décalage manipulent eux aussi des bits. On ne peut les utiliser qu'avec les types primitifs entiers. L'opérateur de décalage à gauche (<<) a pour résultat la valeur de l'opérande situé à gauche de l'opérateur, décalée vers la gauche du nombre de bits spécifié à droite de l'opérateur (en insérant des zéros dans les bits de poids faible). L'opérateur signé de décalage à droite (>>) a pour résultat la valeur de l'opérande situé à gauche de l'opérateur, décalée vers la droite du nombre de bits spécifié à droite de l'opérateur. L'opérateur signé de décalage à droite >> étend le signe : si la valeur est positive, des zéros sont insérés dans les bits de poids fort ; si la valeur est négative, des uns sont insérés dans les bits de poids fort. Java comprend également un opérateur de décalage à droite non signé >>>, qui étend les zéros : quel que soit le signe, des zéros sont insérés dans les bits de poids fort. Cet opérateur n'existe pas en C ou C++.
t t t
If you shift a char, byte, or short, it will be promoted to int before the shift takes place, and the result will be an int. Only the five low-order bits of the right-hand side will be used. This prevents you from shifting more than the number of bits in an int. If you’re operating on a long, you’ll get a long result. Only the six low-order bits of the right-hand side will be used so you can’t shift more than the number of bits in a long.
t Si on décale un char, byte, ou short, il sera promu en int avant le décalage, et le résultat sera un int. Seuls seront utilisés les cinq bits de poids faible de la valeur de décalage, afin de ne pas décaler plus que le nombre de bits dans un int. Si on opère avec un long, le résultat sera un long. Seuls les six bits de poids faible de la valeur de décalage seront utilisés, on ne peut donc décaler un long d'un nombre de bits supérieur à celui qu'il contient.
t t t
Shifts can be combined with the equal sign (<<= or >>= or >>>=). The lvalue is replaced by the lvalue shifted by the rvalue. There is a problem, however, with the unsigned right shift combined with assignment. If you use it with byte or short you don’t get the correct results. Instead, these are promoted to int and right shifted, but then truncated as they are assigned back into their variables, so you get -1 in those cases. The following example demonstrates this:
t Les décalages peuvent être combinés avec le signe égal (<<=, >>= ou >>>=). La lvalue est remplacée par la lvalue décalée de la valeur rvalue. Il y a un problème, toutefois, avec le décalage à droite non signé combiné à une affectation. Son utilisation avec un byte ou un short ne donne pas un résultat correct. En réalité, l'opérande est promu en int, décalé à droite, puis tronqué comme s'il devait être affecté dans sa propre variable, et dans ce cas on obtient -1. L'exemple suivant démontre cela :
t t t
//: c03:URShift.java // Test of unsigned right shift. public class URShift { public static void main(String[] args) { int i = -1; i >>>= 10; System.out.println(i); long l = -1; l >>>= 10; System.out.println(l); short s = -1; s >>>= 10; System.out.println(s); byte b = -1; b >>>= 10; System.out.println(b); b = -1; System.out.println(b>>>10); } } ///:~ t
//: c03:URShift.java
// Test du décalage à droite non signé.

public class URShift {
  public static void main(String[] args) {
    int i = -1;
    i >>>= 10;
    System.out.println(i);
    long l = -1;
    l >>>= 10;
    System.out.println(l);
    short s = -1;
    s >>>= 10;
    System.out.println(s);
    byte b = -1;
    b >>>= 10;
    System.out.println(b);
    b = -1;
    System.out.println(b>>>10);
  }
} ///:~
t t t
In the last line, the resulting value is not assigned back into b, but is printed directly and so the correct behavior occurs.
t Dans la dernière ligne, la valeur résultante n'est pas réaffectée à b, mais directement imprimée et dans ce cas le comportement est correct.
t t t
Here’s an example that demonstrates the use of all the operators involving bits:
t Voici un exemple montrant l'utilisation de tous les opérateurs travaillant sur des bits :
t t t
//: c03:BitManipulation.java // Using the bitwise operators. import java.util.*; public class BitManipulation { public static void main(String[] args) { Random rand = new Random(); int i = rand.nextInt(); int j = rand.nextInt(); pBinInt("-1", -1); pBinInt("+1", +1); int maxpos = 2147483647; pBinInt("maxpos", maxpos); int maxneg = -2147483648; pBinInt("maxneg", maxneg); pBinInt("i", i); pBinInt("~i", ~i); pBinInt("-i", -i); pBinInt("j", j); pBinInt("i & j", i & j); pBinInt("i | j", i | j); pBinInt("i ^ j", i ^ j); pBinInt("i << 5", i << 5); pBinInt("i >> 5", i >> 5); pBinInt("(~i) >> 5", (~i) >> 5); pBinInt("i >>> 5", i >>> 5); pBinInt("(~i) >>> 5", (~i) >>> 5); long l = rand.nextLong(); long m = rand.nextLong(); pBinLong("-1L", -1L); pBinLong("+1L", +1L); long ll = 9223372036854775807L; pBinLong("maxpos", ll); long lln = -9223372036854775808L; pBinLong("maxneg", lln); pBinLong("l", l); pBinLong("~l", ~l); pBinLong("-l", -l); pBinLong("m", m); pBinLong("l & m", l & m); pBinLong("l | m", l | m); pBinLong("l ^ m", l ^ m); pBinLong("l << 5", l << 5); pBinLong("l >> 5", l >> 5); pBinLong("(~l) >> 5", (~l) >> 5); pBinLong("l >>> 5", l >>> 5); pBinLong("(~l) >>> 5", (~l) >>> 5); } static void pBinInt(String s, int i) { System.out.println( s + ", int: " + i + ", binary: "); System.out.print(" "); for(int j = 31; j >=0; j--) if(((1 << j) & i) != 0) System.out.print("1"); else System.out.print("0"); System.out.println(); } static void pBinLong(String s, long l) { System.out.println( s + ", long: " + l + ", binary: "); System.out.print(" "); for(int i = 63; i >=0; i--) if(((1L << i) & l) != 0) System.out.print("1"); else System.out.print("0"); System.out.println(); } } ///:~ t
//: c03:BitManipulation.java
// Utilisation des opérateurs bit à bit.
import java.util.*;

public class BitManipulation {
  public static void main(String[] args) {
    Random rand = new Random();
    int i = rand.nextInt();
    int j = rand.nextInt();
    pBinInt("-1", -1);
    pBinInt("+1", +1);
    int maxpos = 2147483647;
    pBinInt("maxpos", maxpos);
    int maxneg = -2147483648;
    pBinInt("maxneg", maxneg);
    pBinInt("i", i);
    pBinInt("~i", ~i);
    pBinInt("-i", -i);
    pBinInt("j", j);
    pBinInt("i & j", i & j);
    pBinInt("i | j", i | j);
    pBinInt("i ^ j", i ^ j);
    pBinInt("i << 5", i << 5);
    pBinInt("i >> 5", i >> 5);
    pBinInt("(~i) >> 5", (~i) >> 5);
    pBinInt("i >>> 5", i >>> 5);
    pBinInt("(~i) >>> 5", (~i) >>> 5);

    long l = rand.nextLong();
    long m = rand.nextLong();
    pBinLong("-1L", -1L);
    pBinLong("+1L", +1L);
    long ll = 9223372036854775807L;
    pBinLong("maxpos", ll);
    long lln = -9223372036854775808L;
    pBinLong("maxneg", lln);
    pBinLong("l", l);
    pBinLong("~l", ~l);
    pBinLong("-l", -l);
    pBinLong("m", m);
    pBinLong("l & m", l & m);
    pBinLong("l | m", l | m);
    pBinLong("l ^ m", l ^ m);
    pBinLong("l << 5", l << 5);
    pBinLong("l >> 5", l >> 5);
    pBinLong("(~l) >> 5", (~l) >> 5);
    pBinLong("l >>> 5", l >>> 5);
    pBinLong("(~l) >>> 5", (~l) >>> 5);
  }
  static void pBinInt(String s, int i) {
    System.out.println(
      s + ", int: " + i + ", binary: ");
    System.out.print("   ");
    for(int j = 31; j >=0; j--)
      if(((1 << j) &  i) != 0)
        System.out.print("1");
      else
        System.out.print("0");
    System.out.println();
  }
  static void pBinLong(String s, long l) {
    System.out.println(
      s + ", long: " + l + ", binary: ");
    System.out.print("   ");
    for(int i = 63; i >=0; i--)
      if(((1L << i) & l) != 0)
        System.out.print("1");
      else
        System.out.print("0");
    System.out.println();
  }
} ///:~
t t t
The two methods at the end, pBinInt( ) and pBinLong( ) take an int or a long, respectively, and print it out in binary format along with a descriptive string. You can ignore the implementation of these for now.
t Les deux dernières méthodes, pBinInt( ) et pBinLong( ) sont appelées respectivement avec un int et un long, et l'impriment en format binaire avec une description. Nous ne parlerons pas de cette implémentation pour le moment.
t t t
You’ll note the use of System.out.print( ) instead of System.out.println( ). The print( ) method does not emit a new line, so it allows you to output a line in pieces.
t Remarquez l'utilisation de System.out.print( ) au lieu de System.out.println( ). La méthode print( ) n'émet pas de retour-chariot, et permet ainsi d'imprimer une ligne en plusieurs fois.
t t t
As well as demonstrating the effect of all the bitwise operators for int and long, this example also shows the minimum, maximum, +1 and -1 values for int and long so you can see what they look like. Note that the high bit represents the sign: 0 means positive and 1 means negative. The output for the int portion looks like this:
t Cet exemple montre l'effet de tous les opérateurs bit à bit pour les int et les long, mais aussi ce qui se passe avec les valeurs minimale, maximale, +1 et -1, pour un int et pour un long. Noter que le bit de poids le plus fort représente le signe : 0 signifie positif, 1 négatif. Voici la sortie pour la partie int :
t t t
-1, int: -1, binary: 11111111111111111111111111111111 +1, int: 1, binary: 00000000000000000000000000000001 maxpos, int: 2147483647, binary: 01111111111111111111111111111111 maxneg, int: -2147483648, binary: 10000000000000000000000000000000 i, int: 59081716, binary: 00000011100001011000001111110100 ~i, int: -59081717, binary: 11111100011110100111110000001011 -i, int: -59081716, binary: 11111100011110100111110000001100 j, int: 198850956, binary: 00001011110110100011100110001100 i & j, int: 58720644, binary: 00000011100000000000000110000100 i | j, int: 199212028, binary: 00001011110111111011101111111100 i ^ j, int: 140491384, binary: 00001000010111111011101001111000 i << 5, int: 1890614912, binary: 01110000101100000111111010000000 i >> 5, int: 1846303, binary: 00000000000111000010110000011111 (~i) >> 5, int: -1846304, binary: 11111111111000111101001111100000 i >>> 5, int: 1846303, binary: 00000000000111000010110000011111 (~i) >>> 5, int: 132371424, binary: 00000111111000111101001111100000 t
-1, int: -1, binary:
   11111111111111111111111111111111
+1, int: 1, binary:
   00000000000000000000000000000001
maxpos, int: 2147483647, binary:
   01111111111111111111111111111111
maxneg, int: -2147483648, binary:
   10000000000000000000000000000000
i, int: 59081716, binary:
   00000011100001011000001111110100
~i, int: -59081717, binary:
   11111100011110100111110000001011
-i, int: -59081716, binary:
   11111100011110100111110000001100
j, int: 198850956, binary:
   00001011110110100011100110001100
i & j, int: 58720644, binary:
   00000011100000000000000110000100
i | j, int: 199212028, binary:
   00001011110111111011101111111100
i ^ j, int: 140491384, binary:
   00001000010111111011101001111000
i << 5, int: 1890614912, binary:
   01110000101100000111111010000000
i >> 5, int: 1846303, binary:
   00000000000111000010110000011111
(~i) >> 5, int: -1846304, binary:
   11111111111000111101001111100000
i >>> 5, int: 1846303, binary:
   00000000000111000010110000011111
(~i) >>> 5, int: 132371424, binary:
   00000111111000111101001111100000
t t t
The binary representation of the numbers is referred to as signed two’s complement.
t La représentation binaire des nombres est dite en complément à deux signé.
t t t
t t t
t t
\\\
///
t t t
t
     
Sommaire Le site de Bruce Eckel