“我想告訴你如何合併字符串。合併或連接字符串的過程通常使用簡稱“連接”來表示。貓愛好者會發現它很容易記住: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;
該程序將無法編譯!
加法運算是從左到右執行的,所以我們得到:如果我們給一個數字加上一隻貓,沒有自動的字符串轉換。
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;

“是時候從迭戈那裡完成一些任務了。”