
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
String Concatenation in Java
String concatenation is an operation to concatenate two or more strings. In Java, we can concatenate strings using the different approaches. The following are some of the approaches to concatenate the strings:
Using + operator
Using string concat() method
Using stringBuilder or stringBuffer class
String concatenation using + operator
The + operator is a simple way to concatenate two strings It performs the concatenation operation directly between two operands (strings). This is a common method used due to its simplicity.
Example
Following example shows string concatenation by using "+" operator method
public class ConncatSample { public static void main(String []args) { String s1 = "Hello"; String s2 = "world"; String res = s1 + s2; System.out.print("Concatenation result:: "); System.out.println(res); } }
output
Concatenation result:: Helloworld
String concatenation using concat() method
The string concat() method joins one string to the end of another string. It combines the two strings and returns the result. If any of the strings is null, it throws a NullPointerException.
Example
Following example shows concatenation string using concat() method
public class HelloWorld { public static void main(String []args) { String s = "Hello"; s = s.concat("world"); System.out.print(s); } }
output
Helloword
Using stringBuilder or stringBuffer class
The class StringBuilder provides append() method for performing concatenation operation, It takes various types of input arguments, that is Objects, StringBuilder, int, char, CharSequence, boolean, float, double. stringbuilder is the fastest and most popular way of concatenating strings in java.
Example
Following example shows concatenation of strings using stringBuilder or stringBuffer class
public class StringBuilderExample { public static void main(String[] args) { String firstName = "Mark"; String lastName = "Smith"; // Using StringBuilder for efficient string concatenation StringBuilder sb = new StringBuilder(); sb.append("Hello, "); sb.append(firstName); sb.append(" "); sb.append(lastName); String result = sb.toString(); System.out.println(result); } }
output
Hello, Mark Smith