Memento Java

Table des matières :

Primitives / Types simples en Java

  • boolean : 1 bit true / false (may not be cast into any other type of variable nor may any other variable be cast into a boolean)
  • byte : 8 bit signed integer ranging from -128 to 127.
  • char : 16 bit (2 bytes), unsigned, Unicode, 0 to 65,535, default value '\u0000'
  • short : entier 16 bit (2 bytes), signed integer ranging from -32,768 to 32,767.
  • int : entier 32 bit (4 bytes), signed integer ranging from -2,147,483,648 to 2,147,483,647.
  • long : entier 64 bit (8 bytes), signed integer ranging from -9,223,372,036,854,775,808 (-9.22E18) to +9,223,372,036,854,775,807 (9.22E18).
  • float : réel 32 bits (4 bytes) IEEE 754 - from 1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative).
  • double : réel 64 bits (8 bytes) IEEE 754 - from 4.94065645841246544e-324d to 1.79769313486231570e+308d
All numeric types may be cast into other numeric types (byte, int, short, long, float, double). When lossy casts are done (e.g. int to byte) the conversion is done modulo the length of the smaller type.

Classes de type Number

  • Sous classes finales de Number
    • Byte
    • Short
    • Integer
    • Long
    • Float
    • Double
  • Méthodes statiques (sur tous les type de Number)
    • public static X valueOf(String): parse une String et retourne un objet de type Number.
    • public static x parseX(String): parse une String et retourne une primitive.
    • public static String toString(x): to String pour une primitive.
  • Méthodes statiques (Integer et Long)
    • public static String toBinaryString(x)
    • public static String toHexString(x)
    • public static String toOctalString(x)
  • Tous les types Number
    • Constructeur avec type simple
    • Constructeur avec String
    • Methode toString() redéfinit pour retourner la valeur sous forme de String
  • Méthodes de la classe abstraite Number
    • byte byteValue()
    • double doubleValue()
    • float floatValue()
    • int intValue()
    • long longValue()
    • short shortValue()

Operators / Opérateurs

  • Numériques
    • +, -, *, \
    • % : modulo / remainder
    • ++, --
  • Binaires
    • &: AND
    • | : OR
    • ^ : XOR
    • >> << : shift bits right / left
    • >>>
    • ~ : bitwise NOT
  • Comparaison
    • >, <
    • >=, <=
    • ==, !=
  • Booléen
    • && :AND
    • || : OR
    • ! : NOT

Keywords - Mots réservés

  • abstract: declares that a class or method is abstract
  • assert: to specify assertions by default assertions are disabled (Java 1.4)
  • boolean: declares a boolean variable or return type
  • break: prematurely exits a loop
  • byte: declares a byte variable or return type
  • case: one case in a switch statement
  • catch: handle an exception
  • char: declares a character variable or return type
  • class: signals the beginning of a class definition
  • continue: prematurely return to the beginning of a loop
  • const: reserved by Java but are not actually implemented
  • default: default action for a switch statement
  • do: begins a do while loop
  • double: declares a double variable or return type
  • else: signals the code to be executed if an if statement is not true
  • extends: specifies the class which this class is a subclass of
  • false: it is not a keyword but rather a boolean literal
  • final: declares that a class may not be subclassed or that a field or method may not be overridden
  • finally: declares a block of code guaranteed to be executed
  • float: declares a floating point variable or return type
  • for: begins a for loop
  • goto: reserved by Java but are not actually implemented
  • if: execute statements if the condition is true
  • implements: declares that this class implements the given interface
  • import: permit access to a class or group of classes in a package
  • instanceof: tests whether an object is an instanceof a class
  • int: declares an integer variable or return type
  • interface: signals the beginning of an interface definition
  • long: declares a long integer variable or return type
  • native: declares that a method is implemented in native code
  • new: allocates a new object
  • package: defines the package in which this source code file belongs
  • private: declares a method or member variable to be private
  • protected: declares a class, method or member variable to be protected
  • public: declares a class, method or member variable to be public
  • return: returns a value from a method
  • short: declares a short integer variable or return type
  • static: declares that a field or a method belongs to a class rather than an object
  • strictfp: declares that a method or class must be run with exact IEEE 754 semantics (Java 1.2)
  • super: a reference to the parent of the current object
  • switch: tests for the truth of various possible cases
  • synchronized: Indicates that a section of code is not thread-safe
  • this: a reference to the current object
  • throw: throw an exception
  • throws: declares the exceptions thrown by a method
  • transient: This field should not be serialized
  • true: it is not a keyword but rather a boolean literal
  • try: attempt an operation that may throw an exception
  • void: declare that a method does not return a value
  • volatile: Warns the compiler that a variable changes asynchronously
  • while: begins a while loop

Exceptions / Errors

Hiérarchie Throwable

  • java.lang.Object
    • java.lang.Throwable
      • java.lang.Error
        • various errors
      • java.lang.Exception
        • java.lang.RuntimeException
          • various unchecked exceptions
        • various checked exceptions

Exceptions classiques à utiliser

  • RuntimeException
    • IllegalArgumentException : Argument invalide
    • NullPointerException : Lorsqu'un NullPointerException arrive, il est parfois bon de détailler un message pour rendre le debuggage plus facile.
    • ArrayIndexOutOfBoundsException : Détailler le message si besoin
    • ClassCastException : Détailler le message si besoin
    • NumberFormatException : A utiliser si besoin
Exemple d'utilisation :
Dans un cas de programmation générique, il est parfois difficile de retrouver la cause d'une erreur, une solution à cela est de détailler des exceptions telles que NullPointerException. En effet, la cause d'un NullPointer peut être diverse et le simple fait de détailler le message d'erreur avec le contexte permet souvent de résoudre beaucoup plus facilement le bug.

Number et encoding

Integer.toBinaryString(0) = 0 Integer.toBinaryString(1) = 1 Integer.toBinaryString(2) = 10 Integer.toBinaryString(128) = 10000000 Integer.toBinaryString(Integer.MAX_VALUE) = 1111111111111111111111111111111 Integer.toBinaryString(Integer.MIN_VALUE) = 10000000000000000000000000000000 Integer.toBinaryString(Integer.MIN_VALUE+1) = 10000000000000000000000000000001 Integer.toBinaryString(-128) = 11111111111111111111111110000000 Integer.toBinaryString(-2) = 11111111111111111111111111111110 Integer.toBinaryString(-1) = 11111111111111111111111111111111 Integer.MAX_VALUE + 1 == Integer.MIN_VALUE
128 >> 1 = 64 128 : 00000000000000000000000010000000 64 : 00000000000000000000000001000000 128 >> 2 = 32 128 : 00000000000000000000000010000000 32 : 00000000000000000000000000100000 128 >> 3 = 16 128 : 00000000000000000000000010000000 16 : 00000000000000000000000000010000 128 >> 10 = 0 128 : 00000000000000000000000010000000 0 : 00000000000000000000000000000000 .-128 >> 1 = -64 .-128 : 11111111111111111111111110000000 .-64 : 11111111111111111111111111000000 .-128 >> 2 = -32 .-128 : 11111111111111111111111110000000 .-32 : 11111111111111111111111111100000 .-128 >> 3 = -16 .-128 : 11111111111111111111111110000000 .-16 : 11111111111111111111111111110000 .-128 >> 10 = -1 .-128 : 11111111111111111111111110000000 .-1 : 11111111111111111111111111111111
128 << 1 = 256 128 : 00000000000000000000000010000000 256 : 00000000000000000000000100000000 128 << 2 = 512 128 : 00000000000000000000000010000000 512 : 00000000000000000000001000000000 128 << 3 = 1024 128 : 00000000000000000000000010000000 1024 : 00000000000000000000010000000000 .-128 << 1 = -256 .-128 : 11111111111111111111111110000000 .-256 : 11111111111111111111111100000000 .-128 << 2 = -512 .-128 : 11111111111111111111111110000000 .-512 : 11111111111111111111111000000000 .-128 << 3 = -1024 .-128 : 11111111111111111111111110000000 .-1024 : 11111111111111111111110000000000
128 >>> 1 = 64 128 : 00000000000000000000000010000000 64 : 00000000000000000000000001000000 128 >>> 2 = 32 128 : 00000000000000000000000010000000 32 : 00000000000000000000000000100000 128 >>> 3 = 16 128 : 00000000000000000000000010000000 16 : 00000000000000000000000000010000 128 >>> 10 = 0 128 : 00000000000000000000000010000000 0 : 00000000000000000000000000000000 .-128 >>> 1 = 2147483584 .-128 : 11111111111111111111111110000000 2147483584 : 01111111111111111111111111000000 .-128 >>> 2 = 1073741792 .-128 : 11111111111111111111111110000000 1073741792 : 00111111111111111111111111100000 .-128 >>> 3 = 536870896 .-128 : 11111111111111111111111110000000 536870896 : 00011111111111111111111111110000 .-128 >>> 10 = 4194303 .-128 : 11111111111111111111111110000000 4194303 : 00000000001111111111111111111111

Mathématiques et nombres

java.util.Math: Classe utilitaire pour traiter des nombres
  • Constantes
    • E (double): 2.7182818284590452354
    • PI (double): 3.14159265358979323846
  • abs, min, max: Différentes méthodes existent suivant le type (number peux représenter int, long, float ou double)
    • public static number abs(number): Returns the absolute value
    • public static number max(number, number): Returns the greater of two values.
    • public static number min(number, number): Returns the smaller of two values.
  • Méthodes d'arondi: La plupart de ces méthodes utilisent des types double
    • public static double ceil(double a): Returns the smallest (closest to negative infinity) double value that is not less than the argument and is equal to a mathematical integer.
    • public static double floor(double a): Returns the largest (closest to positive infinity) double value that is not greater than the argument and is equal to a mathematical integer.
    • public static double rint(double a): Returns the double value that is closest in value to the argument and is equal to a mathematical integer. If two double values that are mathematical integers are equally close, the result is the integer value that is even.
    • public static long round(double a): Returns the closest long to the argument. The result is equal to the value of the expression:(long)Math.floor(a + 0.5d)
    • public static int round(float a): Returns the closest int to the argument.
  • cosinus, sinus, ...: Toutes les méthodes utilisent des radians (double)
    • public static double cos(double a)
    • public static double cos(double a)
    • public static double tan(double a)
    • public static double acos(double a)
    • public static double asin(double a)
    • public static double atan(double a)
    • public static double toDegrees(double angrad)
  • Autres méthodes
    • public static double log(double a): Returns the natural logarithm (base e) of a double value.
    • public static double exp(double a): Returns Euler's number e raised to the power of a double value.
    • public static double pow(double a, double b): Returns the value of the first argument raised to the power of the second argument.
    • public static double random(): Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
    • public static double sqrt(double a): Returns the correctly rounded positive square root of a double value.
    • public static double toRadians(double angdeg): onverts an angle measured in degrees to an approximately equivalent angle measured in radians.

Math.round(-2.2) = -2 Math.round(-2.5) = -2 Math.round(-2.7) = -3 Math.round(2.2) = 2 Math.round(2.5) = 3 Math.round(2.7) = 3
Math.ceil(-2.2) = -2.0 Math.ceil(-2.5) = -2.0 Math.ceil(-2.7) = -2.0 Math.ceil(2.2) = 3.0 Math.ceil(2.5) = 3.0 Math.ceil(2.7) = 3.0
Math.floor(-2.2) = -3.0 Math.floor(-2.5) = -3.0 Math.floor(-2.7) = -3.0 Math.floor(2.2) = 2.0 Math.floor(2.5) = 2.0 Math.floor(2.7) = 2.0
Math.rint(-2.2) = -2.0 Math.rint(-2.5) = -2.0 Math.rint(-2.7) = -3.0 Math.rint(-3.2) = -3.0 Math.rint(-3.5) = -4.0 Math.rint(-3.7) = -4.0 Math.rint(2.2) = 2.0 Math.rint(2.5) = 2.0 Math.rint(2.7) = 3.0 Math.rint(3.2) = 3.0 Math.rint(3.5) = 4.0 Math.rint(3.7) = 4.0

Utilisation des Threads

  • Constantes de la classe Thread
    • MIN_PRIORITY
    • NORM_PRIORITY
    • MAX_PRIORITY
  • Méthodes statiques
    • public static native Thread currentThread(): Returns a reference to the currently executing thread object.
    • public static native void yield(): Causes the currently executing thread object to temporarily pause and allow other threads to execute.
    • public static native void sleep(long millis) throws InterruptedException: Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. The thread does not lose ownership of any monitors.
  • Méthodes publiques importantes: (Non statiques)
    • public final synchronized void join(long millis) throws InterruptedException: Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.
    • public final void join() throws InterruptedException: Waits for this thread to die.
    • public void run()
  • Méthodes publiques d'état: (Non statiques)
    • public final native boolean isAlive(): Tests if this thread is alive. A thread is alive if it has been started and has not yet died.
    • public boolean isInterrupted(): Tests whether this thread has been interrupted.
    • public static int activeCount(): Returns the number of active threads in the current thread's thread group.
    • public final void setPriority(int newPriority)
    • public final int getPriority()
    • public final void setName(String name)
    • public final String getName()
    • public final void setDaemon(boolean on)
    • public final boolean isDaemon()
    • public final ThreadGroup getThreadGroup()
  • Méthodes deprecated: (Ne plus les utiliser)
    • public final void stop()
    • public final void suspend()
    • public final void resume()
    • public native int countStackFrames()
  • Remarques
    • La priorité d'un thread est par défaut la même que le thread qui l'a créé.

Overloading / Overriding

Les deux termes s'appliquent à des situations ou on définit une méthode avec un même nom de méthode que dans la classe parent. Mais ils représentent deux concepts différents.
  • Overloading: même nom mais pas avec la même signature (paramètres différents: nombre, type ou ordre).
  • Overriding: même nom et même signature dans les deux classes.

Garbage collection

Processus automatique (thread de basse priotité) pour libérer l'espace mémoire utilisé par des objets non disponibles.
Vous pouvez dire à la JVM d'exécuter le garbage collection, mais sans avoir la garantie qu'elle va vraiment le faire.

System.gc(); Runtime.getRuntime().gc();
// Mémoire totale controlée par le programme et la JVM Runtime.getRuntime().totalMemory(); // Mémoire libre de votre programme pouvant être utiliser pour de nouveaux besoins Runtime.getRuntime().freeMemory();

Fichiers JAR / Fichiers .class

Différences entre des classes dans un .jar et un répertoire contenant classes.
  • Case sensitive
    • Sous Windows, les fichiers ne sont pas case-sensitive
    • Dans un .jar, les fichiers sont case-sensitive
    • Il faut donc considérer le cas de Windows comme une exception, et toujours tenir compte de la case.
      En effet, les autres OS, comme linux sont aussi case sensitive pour les noms de fichiers.
  • Répertoire parent
    • Dans un jar on ne peut référencer un fichier en utilisant un path relatif du type ../images/
    • L'utilisation des ../ est donc a éviter dans tous les cas pour assurer une compatibilité complète entre un .jar et les classes.

IO - NIO

Read a file / Lecture d'un fichier

ReadFile with FileReader

public static String readFile(File a_file) throws IOException { FileReader file = null; file = new FileReader(a_file); StringBuffer l_stringBuffer = new StringBuffer(); int c = file.read(); while (c != -1) { l_stringBuffer.append((char)c); c = file.read(); } file.close(); String retour = l_stringBuffer.toString(); return retour; }

ReadFile with NIO

public static String readFile(File a_file) throws IOException { FileInputStream fin = new FileInputStream(a_file); FileChannel fc = fin.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(4*1024); StringBuffer l_stringBuffer = new StringBuffer(); while (fc.read(buffer) != -1) { byte[] l_bytes = buffer.array(); String s = new String(l_bytes, 0, buffer.position()); l_stringBuffer.append(s); buffer.clear(); } String retour = l_stringBuffer.toString(); return retour; }

Liens divers

Un mémento de cours
Un petit mémento Java
Et un autre...
Cafe au lait / Cours Java


Article extrait du site Loribel.com.
https://loribel.com/info/memento/java.html