• Courses
  • Tutorials
  • Jobs
  • Practice
  • Contests
July 05, 2022 |10.8K Views
Java Program to Concatenate Two Strings
Description
Discussion


In this video, we will learn how to Concatenate two Strings in Java language.

Examples:
Input String 1: GEEKSFOR
Input String 2: GEEKS

Output String: GEEKSFORGEEKS

Input String 1 : HELLO
Input String 2: WORLD!!

Output : HELLO WORLD!!

Here we see five different methods for string concatenation:
1. Using + operator
2. Using .concat()
3. Using StringBuilder Class
4. Using .format()
5. Using StringJoiner class

We will also look at some of the pros and cons of each method.

The first way is using the + operator. This is a very simple way to concatenate two strings together and can be done with one line of code, but it does not allow for any formatting or trimming.

Another way is using .concat( ) and the StringBuilder class, which allows for a lot more customization than just adding two strings together. It also has a lot more overhead than the other methods because it needs to create an object every time you use it.

The third way is using .format(), which allows for formatting and trimming within your string and can be done with one line of code.

The last method is StringJoiner class. It is a class in java.util package which is used to construct a sequence of characters(strings) separated by a delimiter and optionally starting with a supplied prefix and ending with a given suffix.

Java String Concatenation: https://www.geeksforgeeks.org/java-string-concat-examples/
Merge two strings in Java: https://www.geeksforgeeks.org/alternatively-merge-two-strings-in-java/