String Concatenation

In the String Variables tutorial we output the lines of a verse of ten green bottles, having output various sections of the verse at a time. Sometimes it's necessary to join elements together before outputting them.

Consider the example from the task:

String wallPhrase = " green bottles hanging on the wall";
System.out.print("10");
System.out.print(wallPhrase);
System.out.print(", ");
System.out.print("10");
System.out.print(wallPhrase);
System.out.print(", and if one green bottle should accidentally fall, there'd be ");
System.out.print("9");
System.out.print(wallPhrase)
There are a lot of print statements here.

  1. Take a copy of the 'GreenBottles' project from the String Variables tutorial
  2. Start by simplifying things so that we output an entire line at a time, to do this, join (concatenate) strings together using the + operator as follows:
    String wallPhrase = " green bottles hanging on the wall";
    System.out.print("10" + wallPhrase + ",");
    System.out.print("10" + wallPhrase + ",");
    System.out.print(" and if one green bottle should accidentally fall, there'd be ");
    System.out.print("9" + wallPhrase);
    This results in more succinct, but still readable code.
  3. Run the project to check it works

Task

Taking your copy of the 'if you're happy and you know it task', modify the code so that you print an entire line of the song at a time

Line breaks

At the moment the output from this method all appears on one line, however it would be useful to separate the lines of the song. Whilst we could use System.out's println method in this case, few programmes in reality output text this way, so we need to learn how to add new lines within our text, and it's fairly simple - we just use the text \n inside the string

Task

  1. Amend the code as follows:
    String wallPhrase = " green bottles hanging on the wall";
    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);
  2. Run the programme and check that the output has multiple lines, even though you are not using the println method

Task 2

Amend the 'if you're happy and you know it' code so that it uses the print method instead of println, ensuring that line breaks are included instead.

Escaped characters (using backslash)

Task

Modify the ten green bottles code, so that the word accidentally appears in double quotation marks.