Types de données _______________⇓_______________ ↓ ↓ Types primitives Types références _________________________⇓_________________________ ↓ ↓ ↓ Interface (interface) Classe (class) Tableau (array)
boolean
char
byte
, short
, int
, long
float
, double
byte
→ short
→ int
→ long
char
→ int
int
→ double
float
→ double
int
→ float
long
→ float
long
→ double
long value = intValue;Otherwise you need to manually cast the value of a specific type to another:
int value = (int) longValue;Note that the value might be truncated if it's larger than the supported range of numeric values of the target type:
byte value = (byte) 128; // "value" will be equal to -128When applying a binary operator on operands of distinct types, then the following should be considered:
boolean
peut contenir les valeurs true
ou false
.char
peut contenir des caractères.char c1 = 'a';Une variable de type
char
peut aussi contenir des nombres entiers positifs.char
peut contenir les valeurs suivantes : [0, 65535]cast
est nécessaire pour affecter une valeur entière a une variable de type char
.char c2 = (char) 65535;A character can be expressed as a hexadecimal value using the suffix \u
char c3 = '\u005B';Escape Characters:
escape character | unicode value | name
\" | \u0022 | Double quote \' | \u0027 | Single quote \\ | \u005c | Backslash \t | \u0009 | Tab \n | \u000a | Line feed \r | \u000d | Carriage return \b | \u0008 | BackspaceUnicode escape characters are interpreted before the code get parsed.
System.out.println("\u0022 + \u0022"); System.out.println("" + "");
char c\u0061 = 'x'; System.out.println(ca);
System.out.println("" "");
:System.out.println("\u0022 \u0022");
// the line feed \u000a will cause multiple compiler errors
// invalid unicode: missing the 4 hex digits after \u: \unicode
char
can hold any 16 bit (basic) unicode character.
For the supplementary unicode characters, each unicode character has a code value (code point) which is represented as pairs of 16 bit code units.
When working with strings that might hold supplementary unicode characters,
you should be aware that a char
value might actually hold the code units that represent the supplementary unicode character.
For example, the smiley symbol "🙂" is represented with 2 code units:
String smiley = "🙂"; System.out.println(smiley.length()); // code units count: 2 System.out.println(smiley.codePointCount(0, smiley.length())); // code points count: 1 System.out.println(String.format("%X", (int) smiley.charAt(0))); // first code unit D83D of the smiley character System.out.println(String.format("%X", (int) smiley.charAt(1))); // second code unit DE42 of the smiley character System.out.println(String.format("%X", smiley.codePointAt(0))); // code point 1F642 of the smiley characterIf you need to print all characters of a string, use the
codePoints
method of the String
class:
"mti🙂tek".codePoints().forEach(cp -> System.out.println(new String(Character.toChars(cp))));
m t i 🙂 t e kSee the Java docs API for the usage of
Character.toChars
method:
public static char[] toChars(int codePoint) //Converts the specified character (Unicode code point) to its UTF-16 representation stored in a char array. //If the specified code point is a BMP (Basic Multilingual Plane or Plane 0) value, the resulting char array has the same value as codePoint. //If the specified code point is a supplementary code point, the resulting char array has the corresponding surrogate pair. //Parameters: //codePoint - a Unicode code point //Returns: //a char array having codePoint's UTF-16 representation.
byte
peut contenir à la fois des valeurs positives et négatives.byte
peut contenir les valeurs suivantes : [-128, 127].short
peut contenir à la fois des valeurs positives et négatives.short
peut contenir les valeurs suivantes : [-32768, 32767].int
peut contenir à la fois des valeurs positives et négatives.int
peut contenir les valeurs suivantes : [-(231), (231)-1].long
peut contenir à la fois des valeurs positives et négatives.long
peut contenir les valeurs suivantes : [-(263), (263)-1].long l1 = 1l; long l2 = 1L;
float
peut contenir des nombres réels.float f1 = 1.0; // compiler error: "Type mismatch: cannot convert from double to float" float f2 = (float) 1.0; // OK float f3 = 1.0f; // OKConstant holding the positive infinity of type float:
/** * A constant holding the positive infinity of type float. * It is equal to the value returned by Float.intBitsToFloat(0x7f800000). */ float POSITIVE_INFINITY = 1.0f / 0.0f;Constant holding the negative infinity of type float:
/** * A constant holding the negative infinity of type float. * It is equal to the value returned by Float.intBitsToFloat(0xff800000). */ float NEGATIVE_INFINITY = -1.0f / 0.0f;Constant holding a Not-a-Number (NaN) value of type float:
/** * A constant holding a Not-a-Number (NaN) value of type float. * It is equivalent to the value returned by Float.intBitsToFloat(0x7fc00000). */ float NaN = 0.0f / 0.0f;Check if a variable is not a number:
if(Float.isNaN(f3))The following is always false (use Float.isNaN instead):
if(f3 == Float.NaN)Check if a variable is positive infinity:
if(f3 == Float.POSITIVE_INFINITY)Check if a variable is negative infinity:
if(f3 == Float.NEGATIVE_INFINITY)Check if a variable is a finite floating-point value:
if(Float.isFinite(f3))Check if a variable is either positive infinity or negative infinity:
if(Float.isInfinite(f3))
double
peut contenir des nombres réels.double d1 = 1.0; // OK double d2 = 1.0d; // OKConstant holding the positive infinity of type double:
/** * A constant holding the positive infinity of type double. * It is equal to the value returned by Double.longBitsToDouble(0x7ff0000000000000L). */ double POSITIVE_INFINITY = 1.0 / 0.0;Constant holding the negative infinity of type double:
/** * A constant holding the negative infinity of type double. * It is equal to the value returned by Double.longBitsToDouble(0xfff0000000000000L). */ double NEGATIVE_INFINITY = -1.0 / 0.0;Constant holding a Not-a-Number (NaN) value of type double:
/** * A constant holding a Not-a-Number (NaN) value of type double. * It is equivalent to the value returned by Double.longBitsToDouble(0x7ff8000000000000L). */ double NaN = 0.0d / 0.0;Check if a variable is not a number:
if(Double.isNaN(d1))The following is always false (use Double.isNaN instead):
if(d1 == Double.NaN)Check if a variable is positive infinity:
if(d1 == Double.POSITIVE_INFINITY)Check if a variable is negative infinity:
if(d1 == Double.NEGATIVE_INFINITY)Check if a variable is a finite floating-point value:
if(Double.isFinite(d1))Check if a variable is either positive infinity or negative infinity:
if(Double.isInfinite(d1))
final
.public class MyClass { void foo() { Integer var1; // La variable var1 va toujours être de type Integer !!! } }
final
alors, une fois initialisée, sa valeur ne peut pas être modifiée (autrement dit, la variable ne peut pas référencer un autre objet).public class MyClass { void foo() { Integer var1 = Integer.valueOf(0); final Integer var2 = Integer.valueOf(0); var1 = Integer.valueOf(10); // OK var2 = Integer.valueOf(20); // Compiler error : The final local variable var2 cannot be assigned. It must be blank and not using a compound assignment } }
public class MyClass { void foo() { Integer var1 = Integer.valueOf(0); // OK : l'objet référencé est du même type (Integer) que celui de la variable var1 Object var2 = Integer.valueOf(0); // OK : le type de l'objet référencé (Integer) est un sous-type de celui de la variable var2 (Object) String var3 = var1; // Compiler error : Type mismatch: cannot convert from Integer to String String var4 = var2; // Compiler error : Type mismatch: cannot convert from Object to String } }
public class MyClass { void foo() { Integer var1 = Integer.valueOf(0); Object var2 = Integer.valueOf(0); var1.intValue(); var2.intValue(); // Compiler error : The method intValue() is undefined for the type Object } }
public abstract interface MyInterfaceType {}
public
et abstract
.public
(dans ce cas elle obtiendra l'accès default
).abstract
;
une interface peut contenir des déclarations de méthodes ainsi que des méthodes ayant le modificateur default.protected
ou private
.static
ou final
.public abstract interface MyInterfaceType { public final static Integer ADD_OPERATION_ID = 0; Integer MULTIPLY_OPERATION_ID = 1; }
public
, final
, et static
.public
, final
, et static
;
le compilateur les ajoutent par défaut.protected
ou private
.public abstract interface MyInterfaceType { public abstract Integer addOperation(Integer value1, Integer value2); Integer multiplyOperation(Integer value1, Integer value2); default Integer identity(Integer i) { return i;} }
public
et abstract
.public
et abstract
; le compilateur les ajoutent par défaut.protected
ou private
.final
(à cause du mot clé abstract
), static
, native
, ou strictfp
.abstract
) à moins de les marquées comme default
.extend
) uniquement d'autres interfaces (elle ne peut pas étendre des classes).package com.mtitek.inheritance; interface MyInterface1 { public void doAction1(); } interface MyInterface2 { public void doAction2(); } interface MyInterface3 extends MyInterface1, MyInterface2 { public void doAction3(); }
implements
) plusieurs interfaces.package com.mtitek.inheritance; interface MyInterface1 { public void doAction1(); } interface MyInterface2 { public void doAction2(); } interface MyInterface3 { public void doAction3(); }
/* La classe "SuperClass1" est abstraite, donc elle n'est pas obligée d'implémenter aucune des méthodes des interfaces "MyInterface1" et "MyInterface2". */ abstract class SuperClass1 implements MyInterface1, MyInterface2 { @Override public void doAction1() { } }
/* La classe "SuperClass2" n'est pas obligée d'implémenter la méthode "doAction1" car elle est déjà implémenter par la classe "SuperClass1". */ class SuperClass2 extends SuperClass1 implements MyInterface3 { @Override public void doAction2() { } @Override public void doAction3() { } }
/* La classe "SubClass1" n'est pas obligée d'implémenter aucunes des méthodes car elles sont déjà implémentées par ses superclasses */ class SubClass1 extends SuperClass2 implements MyInterface2 { }
extend
) une seule classe.implements
) plusieurs interfaces.new
).this
.final
, static
, et abstract
.class MyClassType implements MyInterfaceType { MyClassType() { // constructor code } @Override public Integer addOperation(Integer value1, Integer value2) { return value1 + value2; } @Override public Integer multiplyOperation(Integer value1, Integer value2) { return value1 * value2; } }
Object
qui peut contenir un nombre fixe d'éléments du même type (primitive ou référence).int myIntsArray [] = new int[10]; myIntsArray[0] = 3; System.out.println(myIntsArray.length); // 10 System.out.println(myIntsArray[0]); // 3Declare an array that can hold objects:
Object[] myObjectsArray = new Object[5]; myObjectsArray[0] = Integer.valueOf(7); System.out.println(myObjectsArray.length); // 5 System.out.println(myObjectsArray[0]); // 7Declare a String array and initialize it with initial values:
String[] myStringsArray = {"value1", "value2"}; // explicit syntax: String[] myStringsArray = new String[] {"value1", "value2"};Declare an Object array and initialize it with initial values:
Object[] myComplexObjectsArray = { myStringsArray, myObjectsArray, myIntsArray }; // explicit syntax: Object[] myComplexObjectsArray = new Object[] { myStringsArray, myObjectsArray, myIntsArray };Declare a 2 dimensional array and initialize it with initial values:
String[][] myStringsArray2D = {{"value11", "value12"}, {"value21", "value22"}, {"value31", "value32"}, {"value41", "value42"}}; // explicit syntax: String[][] myStringsArray2D = new String[][] {{"value11", "value12"}, {"value21", "value22"}, {"value31", "value32"}, {"value41", "value42"}}; System.out.println(myStringsArray2D.length); // 4 System.out.println(myStringsArray2D[0].length); // 2Declare an empty array:
String[] emptyArray1 = new String[0]; String[] emptyArray2 = {}; String[] emptyArray3 = new String[] {}; System.out.println(emptyArray1.length); // 0 System.out.println(emptyArray2.length); // 0 System.out.println(emptyArray3.length); // 0To iterarte over an array, use "
for each
" loop: for (type element : array) statement
copyOf
" of the "Arrays
" class: Arrays.copyOf(array, array.length)
sort
" of the "Arrays
" class: Arrays.sort(array)