The class java.lang.String is unusual because an operator is defined in the language specifically for the concatenation of the values of two objects of this class:
String tFirstName = new String("James");
String tSurname = new String("Gosling");
String tName = tFirstName + tSurname;
The variable tName now points to
a string object containing the string "JamesGosling".
Perhaps that is not what we were after.
So use this instead:
String tName = tFirstName + " " + tSurname;
The string concatenation operator is very flexible in that it will convert any operand (that is permitted) into a string. Here is an example:
Point tFirstPoint = new Point(100, 200); String tLine = "The point has the value " + tFirstPoint; System.out.println(tLine);This will output:
The point has the value java.awt.Point[x=100,y=200]
If you have a long string literal, the string concatenation operator can be used to help in the layout of the text. For example, the statement:
System.out.println("Lister glared at Rimmer. \"You really are a smeghead\", he said.");
can instead be written as:
System.out.println("Lister glared at Rimmer." +
" \"You really are a smeghead\", he said.");