« J'aimerais t'expliquer comment fusionner des chaînes. Le processus de fusion ou de jointure de chaînes est souvent désigné par le terme 'concaténation'. Les amoureux de chats bilingues le retiendront facilement : con-CAT-é-nation. Je plaisante. »

« Les règles pour la fusion de chaînes sont simples. Si nous 'ajoutons' (avec l'opérateur +) une chaîne et autre chose, alors cet 'autre chose' est implicitement converti en une chaîne via la méthode toString(). »

« C'est à moi que tu parlais, là ? »

« Bon, je vais t'expliquer de façon plus simple. Si nous ajoutons une chaîne, un nombre et un chat, le nombre et le chat sont transformés en chaînes. Voici quelques exemples : »

Code Code équivalent
Cat cat = new Cat();
String text = "The cat is " + cat;
Cat cat = new Cat();
String s = cat.toString();
String text = "The cat is " + s;
int a = 5;
String text = "a is " + a;
int a = 5;
String s = Integer.toString(a);
String text = "a is " + s;
int a = 5;
String text = a + "a is ";
int a = 5;
String s = Integer.toString(a);
String text = s + "a is ";
Cat cat = new Cat();
int a = 5;
String text = "The cat is " + cat + a;
Cat cat = new Cat();
String s1 = cat.toString();
String s2 = Integer.toString(a);
String text = "The cat is " + s1 + s2;
Cat cat = new Cat();
int a = 5;
String text = a + "The cat is " + cat + a;
Cat cat = new Cat();
String s1 = cat.toString();
String s2 = Integer.toString(a);
String s3 = Integer.toString(a);
String text = s3 + "The cat is " + s1 + s2;
Cat cat = new Cat();
int a = 5;
String text = cat + a + "The cat is " + cat + a;
Le programme ne compile pas !
Les opérations d'addition sont exécutées de gauche à droite, donc on obtient :
String text = (((cat + a) + "The cat is ") + cat) + a;
Si tu ajoutes un chat à un nombre, il n'y a plus de conversion de chaîne automatique.
// But you can do this:
Cat cat = new Cat();
int a = 5;
String text = cat + (a + "The cat is ") + cat + a;

// This is the same as:
Cat cat = new Cat();
int a = 5;
String text = ((cat + (a + "The cat is ")) + cat)+a;
Cat cat = new Cat();
String s1 = cat.toString();
String s2 = cat.toString();
String s3 = Integer.toString(a);
String s4 = Integer.toString(a);
String text = s1 + s3 + "The cat is " + s2 + s4;

« Il est temps pour nous d'effectuer quelques missions de Diego. »