Table of Contents
Different Ways to Concatenate String in Java
1. Using + operator
2. Using a String Buffer
3. Using String Builder
4. Using String.concat ()
Performance Analysis of String Concatenation Using Java
Examples of String Concatenation
Example #3
Conclusion
Home Java javaTutorial Java String Concatenation

Java String Concatenation

Aug 30, 2024 pm 03:34 PM
java

In this article, we will explain java string concatenation in detail. Also, we will see different ways in which two or more strings can be concatenated in java. We will also see the performance of string concatenation in java. In addition, there will be java code examples showing concatenation of java strings.

ADVERTISEMENT Popular Course in this category JAVA MASTERY - Specialization | 78 Course Series | 15 Mock Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Different Ways to Concatenate String in Java

Java String concatenation can be defined as the process of joining two or more strings together into a new string. The following are different ways of concatenating a string in java:

  • Using + operator
  • Using String.concat() method
  • Using StringBuilder class
  • Using StringBuffer class

1. Using + operator

This is the simplest way of concatenating java strings. Using the + operator, we can combine more than one string. One important thing to be noted is that the String obtained after concatenation using + operator will be a new String pointing to the fresh memory location in the java heap. If a string object exists in the pool, then it returns the same string object; otherwise, it creates a new object. The following are the most important things to be kept in mind while using the + operator for concatenating strings:

  • Avoid the use of the + operator when concatenating strings in a loop, as it will produce a lot of garbage.
  • Always store references to object returned after concatenating strings using the + operator.
  • + Operator can be used for converting an integer to string in java.

2. Using a String Buffer

This is a more efficient way to concatenate java strings. Using String buffer for concatenating strings does not create a new object of the resulting string. Using String Buffer saves a lot of memory space as compared to using the + operator. When using string buffer for string concatenation, initialize string buffer object with a specified capacity equal to a number of characters in the final concatenated string. This will result in efficient memory usage as well as save time spent during the resizing of characters. The only drawback associated with using string buffer for string concatenation is the synchronization overhead involved in it as a string buffer is thread-safe.

3. Using String Builder

This is the most efficient way to concatenate java strings. Using String builder for concatenating strings does not create a new object of the resulting string. Using String Builder saves a lot of memory space as compared to using the + operator. When using string builder for string concatenation, initialize string builder object with a specified capacity equal to a number of characters in the final concatenated string. This will result in efficient memory usage as well as save time spent during the resizing of characters. Using a string builder is considered better than using a string buffer because there is no synchronization overhead involved when using a string builder.

4. Using String.concat ()

This is implemented internally using string buffer or string builder append methods which are described above.

Performance Analysis of String Concatenation Using Java

From the four-string concatenation methods described earlier, using the + operator is preferred when fewer strings are to be concatenated. But as the number of strings to be concatenated becomes larger, the performance of the + operator degrades a large number of objects are created due to string immutability. When several strings are to be concatenated, a string builder is preferred as it provides string mutability.

Syntax:

Here is the basic syntax of string concatenation in java:

1. Using + operator:

// method accepting strings to be concatenated
public String concatString(String s1, String s2){
String s3= s1+s2;   // using + operator
return s3;
}
Copy after login

2. Using String.concat() method:

public String concatString(String s1){
String s= "First";
String s2=s.concat(s1);   // using concat method
return s2;
}
Copy after login

3. Using a StringBuffer:

StringBuffer sb= new StringBuffer(capacity); // create string buffer instance
sb.append("first").append(" ").append("second");    // call append method specifying string to be concatenated
Copy after login

4. Using StringBuilder:

StringBuilder sb= new StringBuilder(capacity); // create string builder instance
sb.append("first").append(" ").append("second");    // call append method specifying string to be concatenated
Copy after login

Examples of String Concatenation

Given below are the examples:

Example #1

Let us see a basic example of string concatenation using the + operator and concat () method.

Code:

package com.edubca.stringconcatenation;
public class StringconcatDemo{
public static void main(String args[]){
String s1= "This";
String s2= "Is";
String s3= "Edubca";
String s4="Training";
// Using + operator
String concatenatedstr= s1 + " " + s2 +" " + s3 + " " + s4;
System.out.println("String after concatenation is  :: " + concatenatedstr);
//using concat method
String concatenatedstr1= s1.concat(" ").concat(s2).concat(" ").concat(s3).concat(" ").concat(s4);
System.out.println("String after concatenation using concat method is  :: " + concatenatedstr1);
}
}
Copy after login

Output:

Java String Concatenation

Example #2

In this example, we will see how to string concatenation is achieved using a string buffer in java.

Code:

package com.edubca.stringconcatenation;
public class StringconcatDemo{
public static void main(String args[]){
String s1= "This";
String s2= "Is";
String s3= "Edubca";
String s4="Training";
// create StringBuffer Instance
StringBuffer sb=new StringBuffer("Edubca");
//call append method for string concatenate
StringBuffer concatenatedstr=sb.append(" ").append("Java").append(" ").append("Training");
System.out.println("Concatenated String using String Buffer is :: " + concatenatedstr );
}
}
Copy after login

Output:

Java String Concatenation

Example #3

In this example, we will see how to string concatenation is achieved using a string builder in java.

Code:

package com.edubca.stringconcatenation;
public class StringconcatDemo{
public static void main(String args[]){
String s1= "This";
String s2= "Is";
String s3= "Edubca";
String s4="Training";
// create StringBuilder Instance
StringBuilder sb=new StringBuilder ("Edubca");
//call append method for string concatenate
StringBuilder concatenatedstr=sb.append(" ").append("Java").append(" ").append("Training");
System.out.println("Concatenated String using String Builder is :: " + concatenatedstr );
}
}
Copy after login

Output:

Java String Concatenation

Note: It is important to note that we should prefer StringBuilder over StringBuffer as a String buffer that consumes extra time in synchronization. But in a multithreaded environment, it is advisable to go for StringBuffer.

Conclusion

From the above discussion, we have a clear understanding of string concatenation in java, how it’s achieved, and what are different ways to concatenate java strings. Also, java code examples provide a clear understanding of concatenating strings.

The above is the detailed content of Java String Concatenation. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles