Concatenation and Escape Sequences
Explore how to combine strings in Java using the + operator, += shorthand, and concat() method. Understand implicit conversion when concatenating primitives and strings. Learn to correctly include special characters in strings using escape sequences such as \" for quotes and \n for new lines.
What is concatenation?
An act of linking things or objects together in a series is called concatenation. For example, if we have two strings “Help” and “Java”, the result of their concatenation will be “HelpJava”.
Concatenation in Java
Concatenation using the + operator
Strings are commonly concatenated using the + operator. Here’s an example:
Initially, there are two strings: s1 and s2. Look at line 7. We join s1 and s2 with a + operator, and store the concatenated result back in the string, s1. Notice that when we print s1, it displays HelpJava without any space between the two strings.
A shortcut to write s1 = s1 + s2 exists. We can merge the = and + operator in a single operator: +=. Replace line 7 with the s1 += s2 statement. It’s a shorter way to write s1 = s1 + s2.
How about making the output more descriptive? Let’s do it.
At line 8, we are concatenating the following six strings in total:
- "Concatenation of "
s1- " and "
s2- " is: "
s3.
🧐 Note: We make sure to add a space ...