Java String Concatenation

String concatenation is the operation of joining two or more strings together. In Java, you can concatenate strings using the + operator or the concat() method.

Key Topics

1. Using the + Operator

The simplest way to concatenate strings is by using the + operator.

public class ConcatenationExample {
    public static void main(String[] args) {
        String firstName = "John";
        String lastName = "Doe";
        String fullName = firstName + " " + lastName;
        System.out.println("Full Name: " + fullName);
    }
}

2. Using the concat() Method

You can also use the concat() method to join strings.

public class ConcatMethodExample {
    public static void main(String[] args) {
        String hello = "Hello";
        String world = "World";
        String greeting = hello.concat(", ").concat(world).concat("!");
        System.out.println(greeting);
    }
}

3. Using StringBuilder

For concatenating multiple strings efficiently, especially in loops, use StringBuilder.

public class StringBuilderExample {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        sb.append("Java");
        sb.append(" ");
        sb.append("Programming");
        String result = sb.toString();
        System.out.println(result);
    }
}

Key Takeaways

  • The + operator is convenient for simple string concatenation.
  • The concat() method can also be used but is less flexible.
  • StringBuilder is more efficient for concatenating strings in loops or when dealing with large amounts of data.