"Vorrei dirti come unire le stringhe. Il processo di unione o unione delle stringhe viene spesso indicato usando la parola breve 'concatenazione'. Gli amanti dei gatti troveranno facile da ricordare: con-Cat-en-Nation. I sto scherzando ".

"Le regole per unire le stringhe sono semplici. Se 'aggiungiamo' (+) una stringa e qualcos'altro, allora 'qualcos'altro' viene implicitamente convertito in una stringa tramite il metodo toString () . "

"Stavi parlando con me proprio ora?"

"Va bene, te lo spiego in modo più semplice. Se aggiungiamo una stringa, un numero e un gatto, allora sia il numero che il gatto si trasformeranno in stringhe. Ecco alcuni esempi:"

Codice Codice equivalente
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;
Il programma non viene compilato!
Le operazioni di addizione vengono eseguite da sinistra a destra, quindi otteniamo: Se aggiungiamo un gatto a un numero, non c'è conversione automatica di stringhe.
String text = (((cat + a) + "The cat is ") + cat) + a;
// 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;

"È giunto il momento di fare alcuni compiti da Diego."