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
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.
ExampleFollowing 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:: HelloworldString 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.
ExampleFollowing 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
HellowordUsing 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.
ExampleFollowing 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
java_strings.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4