DevAcademia
C++C#CPythonJava
  • Java Basics

  • Java Introduction
  • Java Get Started
  • Java Syntax
  • Java Output
  • Java Comments
  • Java Variables
  • Java Data Types
  • Java Type Casting
  • Java Operators
  • Java Strings
  • Java If...Else
  • Java Switch Statement
  • Java Loops
  • Java Math
  • Java Arrays
  • Java Date
  • Java OOP

  • Java Classes/Objects
  • Java Class Attributes
  • Java Class Methods
  • Java Constructors
  • Java Destructors
  • Java this Keyword
  • Java Modifiers
  • Java Non Modifiers
  • Java Encapsulation
  • Java Packages & API
  • Java Inheritance
  • Java Polymorphism
  • Java Super Keyword
  • Java Inner Classes
  • Java Exception Handling
  • Java Abstraction
  • Java Interfaces
  • Java Enums
  • Java User Input
  • Java Quiz

  • Java Fundamentals Quiz
  • Java Basics

  • Java Introduction
  • Java Get Started
  • Java Syntax
  • Java Output
  • Java Comments
  • Java Variables
  • Java Data Types
  • Java Type Casting
  • Java Operators
  • Java Strings
  • Java If...Else
  • Java Switch Statement
  • Java Loops
  • Java Math
  • Java Arrays
  • Java Date
  • Java OOP

  • Java Classes/Objects
  • Java Class Attributes
  • Java Class Methods
  • Java Constructors
  • Java Destructors
  • Java this Keyword
  • Java Modifiers
  • Java Non Modifiers
  • Java Encapsulation
  • Java Packages & API
  • Java Inheritance
  • Java Polymorphism
  • Java Super Keyword
  • Java Inner Classes
  • Java Exception Handling
  • Java Abstraction
  • Java Interfaces
  • Java Enums
  • Java User Input
  • Java Quiz

  • Java Fundamentals Quiz

Loading Java tutorial…

Loading content
Java BasicsTopic 22 of 59
←PreviousPrevNextNext→

Java String Concatenation - Complete Guide

Introduction to String Concatenation

String concatenation in Java means joining two or more strings together into a single new string. Java offers several approaches for concatenation, each with different efficiency and use cases.

Knowing which method to use helps improve readability and performance, especially when working with large or repeated string operations.

Using the + Operator

The + operator is the simplest and most common way to concatenate strings. While easy to use, repeated concatenation with + in loops can create many intermediate String objects, making it less efficient.

Example
public class PlusOperator {
    public static void main(String[] args) {
        String firstName = "John";
        String lastName = "Doe";
        String fullName = firstName + " " + lastName;
        System.out.println(fullName);

        int age = 30;
        String message = "Name: " + fullName + ", Age: " + age;
        System.out.println(message);

        String a = "A";
        String b = "B";
        String c = "C";
        String result = a + b + c;
        System.out.println(result);

        String nullStr = null;
        String withNull = "Value: " + nullStr;
        System.out.println(withNull);

        String combined = "Sum: " + 10 + 20;
        System.out.println(combined); // "Sum: 1020"

        String correctSum = "Sum: " + (10 + 20);
        System.out.println(correctSum); // "Sum: 30"
    }
}
Output
John Doe
Name: John Doe, Age: 30
ABC
Value: null
Sum: 1020
Sum: 30

Using concat() Method

The concat() method of the String class appends one string to the end of another. Unlike the + operator, it only accepts another string as an argument and throws NullPointerException if null is passed.

Example
public class ConcatMethod {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "World";

        String result = str1.concat(" ").concat(str2);
        System.out.println(result);

        String emptyConcat = str1.concat("");
        System.out.println("Original: " + str1);
        System.out.println("After empty concat: " + emptyConcat);
        System.out.println("Same object? " + (str1 == emptyConcat));

        try {
            String nullConcat = str1.concat(null);
            System.out.println(nullConcat);
        } catch (NullPointerException e) {
            System.out.println("NullPointerException: " + e.getMessage());
        }

        String longString = "A".concat("B").concat("C").concat("D");
        System.out.println(longString);
    }
}
Output
Hello World
Original: Hello
After empty concat: Hello
Same object? true
NullPointerException: Cannot invoke "String.concat(String)" because the argument is null
ABCD

Using StringBuilder and StringBuffer

StringBuilder and StringBuffer are mutable classes designed for efficient string concatenation. StringBuilder is faster but not thread-safe, while StringBuffer is synchronized and safe to use in multi-threaded contexts.

Example
public class StringBuilderBuffer {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        sb.append("Hello").append(" ").append("World");
        System.out.println(sb.toString());

        String chained = new StringBuilder()
            .append("Name: ")
            .append("John")
            .append(", Age: ")
            .append(30)
            .toString();
        System.out.println(chained);

        StringBuffer sbf = new StringBuffer();
        sbf.append("Thread").append("-").append("Safe");
        System.out.println(sbf.toString());

        int iterations = 10000;

        long startTime = System.currentTimeMillis();
        String plusResult = "";
        for (int i = 0; i < iterations; i++) {
            plusResult += "x";
        }
        long plusTime = System.currentTimeMillis() - startTime;

        startTime = System.currentTimeMillis();
        StringBuilder sbLoop = new StringBuilder();
        for (int i = 0; i < iterations; i++) {
            sbLoop.append("x");
        }
        String sbResult = sbLoop.toString();
        long sbTime = System.currentTimeMillis() - startTime;

        System.out.println("+ operator time: " + plusTime + "ms");
        System.out.println("StringBuilder time: " + sbTime + "ms");
    }
}
Output
Hello World
Name: John, Age: 30
Thread-Safe
+ operator time: 108ms
StringBuilder time: 1ms

Best Practices for String Concatenation

  • ✅ Use + for small, simple concatenations
  • ✅ Prefer StringBuilder for repeated concatenations in loops
  • ✅ Use StringBuffer if thread safety is required
  • ✅ Set an initial capacity for StringBuilder/StringBuffer when size is known
  • ✅ Remember String objects are immutable; concatenation creates new objects
  • ✅ Use String.join() when combining collections with delimiters
  • ✅ Consider String.format() for readable formatted strings
  • ✅ Minimize concatenation in performance-critical sections
Test your knowledge: Java String Concatenation - Complete Guide
Quiz Configuration
4 of 10 questions
Sequential
Previous allowed
Review enabled
Early close allowed
Estimated time: 5 min
Java BasicsTopic 22 of 59
←PreviousPrevNextNext→