In the String Concatenation tutorial, we simplified the code by appending strings together (both string variables and string literals). This left us with resulting code similar to this:
System.out.print("10" + wallPhrase + ",\n");
System.out.print("10" + wallPhrase + ",\n");
System.out.print("and if one green bottle should accidentally fall, there'd be ");
System.out.print("9" + wallPhrase);
One option to simplify this further would be to simply concatenate all the strings using the +
operator, however this would result in a very long line of code, and it would be rather unreadable. That said, it would also be useful to have all the song lyrics in one variable that we could print at the end.
Fortunately, we can do this by creating a variable for the song and then re-assigning its value to its current value concatenated with a new string as follows:
String wallPhrase = " green bottles hanging on the wall";
String verse = "10" + wallPhrase + ",\n";
verse = verse + "10" + wallPhrase + ",\n";
verse = verse + "and if one green bottle should accidentally fall, there'd be ";
verse = verse + "9" + wallPhrase;
System.out.println(verse);
The end result is the same, but now verse contains the lyrics for the entire verse
It's a little bit frustrating to have to type the name of the variable twice per line, so Java provides a shorthand way of appending a string - using the +=
operator. This essentially takes the value to the right hand side and appends it to the value on the left hand side of the operator, for example
String burger = "1/4 pounder";
burger += " with cheese";
System.out.println(burger);
will print "1/4 pounder with cheese"
It is important to note that
burger += " with cheese";
is functionally identical toburger = burger + " with cheese";