×

How to Concatenate Two Strings in Java

How to Concatenate Two Strings in Java

Concatenation of two strings means adding the beginning of one string to the end of the other string. Some of the ways to concatenate two strings in Java are mentioned below.

By Using + Operator

The + operator can be used to concatenate the strings. Let’s understand it with the help of the following example.

FileName: StringConcatenationExample.java

 public class StringConcatenationExample
{ 
// main method
public static void main(String argvs[])
{
// Input string
String str1 = "Tutorial & Example";
// Doing the concatenation work
str1 = str1 + " – A Good Site To Learn Java.";
System.out.println(str1);
}
} 

Output:

Tutorial & Example – A Good Site To Learn Java.


Explanation: By looking at the output, it is evident that the + operator concatenates the strings “Tutorial & Example” and “– A Good Site To Learn Java.”

By Using the concat() Method

The concat() method can also be used to do the concatenation work.

Syntax:

public String concat (String  anotherStr)

String anotherStr: represents the string that is being concatenated with the current string.

A String is returned, which is the concatenation of the current string and anotherStr.

The following program illustrates the same.

FileName: StringConcatenationExample1.java

 public class StringConcatenationExample1
{ 
// main method
public static void main(String argvs[])
{
// Input string
String str1 = "Tutorial & Example";
// Doing the concatenation work
str1 = str1.concat(" – A Good Site To Learn Java.");
System.out.println(str1);
}
} 

Output:

Tutorial & Example – A Good Site To Learn Java.


Explanation: In the above program, the + operator is replaced by the concat() method to accomplish the concatenation work. Everything else remains the same. Hence, the output also remains the same.

By Using the append() Method

Another approach is to use the append() method to do the concatenation of the given strings. However, the append() method is not present in the Java String class. Therefore, to apply the append() method, one needs the object of either StringBuilder or StringBuffer class. Observe the following program.

FileName: StringConcatenationExample2.java

 public class StringConcatenationExample2
{ 
// main method
public static void main(String argvs[])
{
// Input string
String str1 = "Tutorial & Example";
// Creating an object of the StringBuilder class
StringBuilder strBldrObj = new StringBuilder(str1);
// Doing the concatenation work
strBldrObj = strBldrObj.append(" – A Good Site To Learn Java.");
// getting the string from the
// object of the StringBuilder class
str1 = strBldrObj.toString();
// displaying the string
System.out.println(str1);
str1 = "Let's visit";
// Creating an object of the StringBuffer class
StringBuffer strBfrObj = new StringBuffer(str1);
// Doing the concatenation work
strBfrObj = strBfrObj.append(" The Tutorial & Example Site Again To Learn Java.");
// getting the string from the
// object of the StringBuffer class
str1 = strBfrObj.toString();
// displaying the string
System.out.println(str1);
}
} 

Output:

 Tutorial & Example – A Good Site To Learn Java.
Let's visit The Tutorial & Example Site Again To Learn Java. 


Explanation: The above program shows that either StringBuilder or StringBuffer class can be used to do the concatenation of string. The concatenation of strings is achieved by invoking the append() method on the objects of the classes StringBuilder or StringBuffer. The toString() method then used to extract the concatenated string from those objects, which is displayed in the output.


Related Topics

Java Continue Keyword

The java keyword ‘continues’ has also been called as java continue statement.The main concepts of the java continue statement or keyword is used in the controlling of the loop structure.Java...

3 minutes read.

Quick Sort in Java

Quick Sort in Java Like merge sort, quick sort also uses the divide and conquer approach to sort the given array or list. In quick sort, the sorting of an array...

6 minutes read.

Java Math log10() Method

The log10() method of Math class returns the base 10 logarithmic value for the specified double argument. Syntax: public static double log10(double a) Parameters: The parameter ‘a’ represents a double value. Return Value: The log10() method...

2 minutes read.

Vector in Java

Java Vector Class The Vector class is a legacy class that implements a growable array of objects. The components that it contains can be accessed using an integer index. The size of...

26 minutes read.

Union in Java

Sets.union() method in Java returns an immutable representation of both the union of two sets. Every element that is present in either backup set is included in the set that...

2 minutes read.

JIT in Java

What is JIT ? JIT stands for " Just in Time Compiler ". It is called "Just in time" because it is called at the very last moment when the interpretation...

5 minutes read.

Types of Assignment Operators in Java

In this tutorial, we are going to study assignment operators and their types in Java language. Before proceeding to the types, let us know the term ‘assignment operator’.  The assignment...

5 minutes read.

if-else Program in Java

if-else Program in Java The if-else program in Java controls which code snippet will execute. The if-else program is very basic and yet very important. Because it checks how well one...

19 minutes read.

Java String trim() method

Java String trim() method returns String after eliminating leading and trailing spaces. Note:- Java String trim() method doesn't trim or omit middle spaces. Syntax: public String trim() Returns: It returns string with omitted leading and...

2 minutes read.

Java throws

Java throws: The Java throws keyword is used with the signature of the method to indicate that the method may raise an exception. The method that uses the Java throws...

3 minutes read.

How to sort a String in Java

Sorting is the process of putting the elements in a certain order, either ascending or descending. Mostly the alphabetical order or natural order is used for a string. In other...

5 minutes read.

Java Pop

The array, linked list, stack, queue, and other data structures are supported by Java programming. The insertion, deletion, and element searching operations are available for every data structure. And Java...

4 minutes read.

Java Math acos() Method

The acos() method of Math class computes the trigonometric Arc Cosine (inverse of cosine ) of an angle. The value returned is between 0.0 to pi. Syntax: public static double acos(double a) Parameters: The...

1 minute read.

Moran Numbers in Java

In this article, we will be acknowledged about the moran numbers in Java, how they are formed, what are the approaches to achieve the moran numbers. Moran Number A moran numbers are...

3 minutes read.

Java List Interface

List interface is used when we have to order a collection which contains duplicate entries. Like an array, the elements of its implementation classes are retrieved and inserted at a...

2 minutes read.

Different Ways to Take Input from User in Java

Any information provided to a system for use is known as user input. Any responsive software or application must include user input. In Java, there are 4 different ways to...

5 minutes read.

Recursion Program in Java

The recursion program in Java demonstrates the usage of recursion. The process by which a function/ method calls itself, again and again, is called recursion. Each recursive call is pushed...

10 minutes read.

Get yesterdays date by no of days in Java

In this tutorial, we are going to learn how to get yesterday’s date by the no of days in Java. Using the Calendar class, one can get the current date....

1 minute read.

Method Overloading In Java

If the same class consists of different methods with the same name and the methods can vary by different number of parameters then it is known as Method Overloading. Method...

2 minutes read.

Java Integer remainder Unsigned() method

The remainderUnsigned() method of Java Integer class returns the unsigned remainder by dividing the first and second argument. Syntax public static int remainderUnsigned(int dividend, int divisor)  Parameters The ‘dividend’ and ‘divisor’ represents the value...

1 minute read.