...

/

Concatenation and Escape Sequences

Concatenation and Escape Sequences

Learn about the operators used in concatenation and escape sequences.

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:

Press + to interact
class ConcatenationDemo1
{
public static void main(String args[])
{
String s1 = "Help";
String s2 = "Java";
s1 = s1 + s2; // Concatenation with + operator
System.out.println(s1);
}
}

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.

Press + to interact
class ConcatenationDemo1
{
public static void main(String args[])
{
String s1 = "Help";
String s2 = "Java";
String s3 = s1 + s2; // Concatenation with + operator
System.out.println("Concatenation of " + s1+ " and " + s2+ " is: " + s3);
}
}

At line 8, we are concatenating the following six strings in total:

  1. "Concatenation of "
  2. s1
  3. " and "
  4. s2
  5. " is: "
  6. s3.

🧐 ...