"Ik zou je willen vertellen hoe je strings kunt samenvoegen. Het proces van het samenvoegen of samenvoegen van strings wordt vaak aangeduid met het korte woord 'aaneenschakeling'. Kattenliefhebbers zullen het gemakkelijk kunnen onthouden: con-Cat-en-Nation. Ik ik maak een grapje ."

"De regels voor het samenvoegen van tekenreeksen zijn eenvoudig. Als we een tekenreeks en iets anders 'toevoegen' (+), dan wordt het 'iets anders' impliciet geconverteerd naar een tekenreeks via de methode toString () . "

"Was je zojuist tegen me aan het praten?"

"Oké, ik zal het op een eenvoudigere manier uitleggen. Als we een string, een nummer en een kat toevoegen, dan worden zowel het nummer als de kat omgezet in strings. Hier zijn enkele voorbeelden:"

Code Gelijkwaardige code
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;
Het programma compileert niet!
De optelbewerkingen worden van links naar rechts uitgevoerd, dus we krijgen: Als we een kat toevoegen aan een getal, is er geen automatische tekenreeksconversie.
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;

"Het is tijd om een ​​paar taken van Diego te doen."