Creating and Combining Strings

Text in Java is held by String objects. A railway's ticket printer builds every line it prints from them.
Creating a String
String from = "Albany";
String to = new String("Boston");
Each line creates a String object, a sequence of characters. The first uses a string literal. The second calls the String constructor with new, the way other objects are created, and passes it the literal "Boston". Both variables hold references to String objects, since String is a class. The literal form is the one programs usually use.
Like Math, String comes from java.lang, so a program needs no extra line to use it.
Concatenation
The + operator joins two strings into one.
String route = from + " to " + to;
This evaluates left to right. from + " to " is "Albany to ", and adding to gives "Albany to Boston". The result is a new String object, and route refers to it.
The += operator joins text onto the string a variable refers to and stores the result back in the variable.
route += " (express)";
Now route refers to a new object, "Albany to Boston (express)". The object "Albany to Boston" wasn't changed. A String object never changes after it's created. Instead, the variable now refers to a different object.
Strings and numbers
A primitive value can be joined to a String. Java converts the value to text first.
Because + is evaluated left to right, where the numbers sit decides whether they're added or joined as text. A ticket shows how many riders it covers and how much a seat upgrade costs.
int adults = 2;
int kids = 1;
double upgrade = 4.5;
String line = adults + kids + " riders, upgrade " + upgrade + adults;
The first + has an int value on each side, so it's addition, and it gives 3. One side of the next + is a String, so that one joins, giving "3 riders, upgrade ". From there each + is joining onto a String. The double joins as 4.5, and adults joins as the digit 2, so line is "3 riders, upgrade 4.52". Writing (upgrade * adults) at the end makes the multiplication happen first, and the text ends in 9.0.
Strings and objects
A String can also be joined to an object. The railway's Seat class documents a toString method.
Method headerDescription
public Seat(int row, String letter)Creates a seat in the given row with the given letter.
public String toString()Returns the seat's row number followed by its letter.
Seat mine = new Seat(22, "A");
System.out.println(mine + " (window)");
The other operand of + is a String, so Java calls mine.toString() without being asked, gets "22A", and prints 22A (window). Every class has a toString method, since every class is a subclass of Object, which has one. A class like Seat gives it a version of its own that describes its objects.