「文字列をマージする方法を説明したいと思います。文字列をマージまたは結合するプロセスは、「連結」という短い言葉を使ってよく呼ばれます。猫好きなら、「con-Cat-en-Nation」と覚えやすいでしょう。冗談だよ。」

「文字列をマージするルールは単純です。文字列と他の何かを「追加」(+) すると、その「他の何か」は toString () メソッドを介して暗黙的に文字列に変換されます

「今、私と話していたんですか?」

「わかりました。もっと簡単に説明します。文字列、数字、猫を追加すると、数字と猫の両方が文字列に変換されます。例をいくつか示します。」

コード 同等のコード
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;
プログラムはコンパイルできません!
加算演算は左から右に実行されるため、次のようになります。数値に cat を加算すると、自動文字列変換は行われません。
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;

「ディエゴからいくつかの任務を遂行する時が来ました。」