Learn Java · lesson 6 of 61 · about 6 minutes
Strings and Concatenation
Print a ticket line for each booking: join text and values with + and +=, and see why row C plus 12 can come out as 79.
What you'll learn
- Join Strings with +
- Mix text and numbers safely
- Grow a String with +=
Joining text
+ joins Strings. As soon as one side is a String, the other side is turned into text, so "Sold: " + 4 is "Sold: 4".
Java works from left to right. "Seats: " + 4 + 2 joins the 4 to the text first, then the 2, giving Seats: 42. But 4 + 2 + " seats" adds the numbers before it meets any text, giving 6 seats.
ticket += "!" adds to the end of ticket. A String can't be changed, so += makes a new one and stores it back in ticket.
A ticket line
public class Main {
public static void main(String[] args) {
String show = "Space Pirates";
int sold = 4;
String ticket = show + " | " + sold + " tickets";
ticket += "!";
System.out.println(ticket);
System.out.println("Seats: " + 4 + 2);
System.out.println(4 + 2 + " seats");
}
}Output
Space Pirates | 4 tickets!
Seats: 42
6 seatsA char is a number
A char is stored as a number: 'C' is 67. So row + 12 adds two numbers and gives 79, not C12. Start with an empty String, "" + row + 12, and everything after it is joined as text.
Two ways to add a seat number
public class Main {
public static void main(String[] args) {
char row = 'C';
System.out.println(row + 12);
System.out.println("" + row + 12);
}
}Output
79
C12Tip
When numbers come out joined (42) or letters come out as numbers (79), look at what's on the left of each +.
Now try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.