Remember that string concatenation is used to dynamically generate messages that can be different depending on context.
We most often use it with variables, let's check an example:
String adjective = "awesome";
String message = "AlgoCademy is ";
// String concatenation & assignment:
message = message + adjective;
System.out.println(message); // Output: AlgoCademy is awesome
We first concatenate message and favoriteAnimal and then we assign the result to message.
Concatenating with +=
Since this is such a common pattern, there is the += operator which does both the concatenation and assignment in one step.
String adjective = "awesome";
String message = "AlgoCademy is ";
// With += operator:
message += adjective;
System.out.println(message); // Output: AlgoCademy is awesome
Concatenating multiple strings:
We can append as many strings as we want using the += operator:
String name = "Andy";
String pet = "dog";
String message = "Hey, ";
message += name;
message += "! Nice ";
message += pet;
message += "!" ;
System.out.println(message); // Output: Hey, Andy! Nice dog!
Assignment
Follow the Coding Tutorial and let's practice with string concatenation!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
