"I'd like to tell you how to merge strings. The process of merging or joining strings is often referred to using the short word 'concatenation'. Cat lovers will find it easy to remember: con-Cat-en-Nation. I'm joking."
"The rules for merging strings are simple. If we 'add' (+) a string and something else, then the 'something else' is implicitly converted to a string via the toString() method."
"Were you talking to me just now?"
"Okay, I'll explain it in an easier way. If we add a string, a number and a cat, then both the number and the cat will be transformed into strings. Here are some examples:"
Code | Equivalent code |
---|---|
|
Cat cat = new Cat(); String s = cat.toString(); String text = "The cat is " + s; |
|
int a = 5; String s = Integer.toString(a); String text = "a is " + s; |
|
int a = 5; String s = Integer.toString(a); String text = s + "a is "; |
|
Cat cat = new Cat(); String s1 = cat.toString(); String s2 = Integer.toString(a); String text = "The cat is " + s1 + s2; |
|
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; |
|
The program won't compile! The addition operations are executed from left to right, so we get: String text = (((cat + a) + "The cat is ") + cat) + a; If we add a cat to a number, there is no automatic string conversion. |
|
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; |
"The time has come to do a few tasks from Diego."
GO TO FULL VERSION