This post demonstrates :
– Different way of concatenating strings in Java.
– concatenate strings using + operator
– concatenate string using String concat() function
– joining strings using StringBuffer/StringBuilder append() method
– joining Strings using join() method added in JDK 8
Method 1 : Using + operator
+ operator can be used to concatenate string.
Example :
String str1 = "Hello"; String str2 = "World"; String str3 = str1 +" " + str2;
The + operator is overloaded. It can add numbers and concatenate strings.
So, here are the rules to keep in mind while using + operator for concatenation:
1. If both operands are numeric, + means numeric addition.
2. If either operand is a String, + means concatenation.
3. The expression is evaluated left to right.
Method 2 : Using String concat() function
String class provides a concat() function that can be used for String concatenation.
Example :
String str4 = str1.concat(" ").concat(str2);
Method 3 : Using StringBuffer or StringBuilder
StringBuffer and StringBuffer classes have an append() method that can be used to concatenate strings.
StringBuilder builder = new StringBuilder(); builder.append(str1).append(" ").append(str2);
Method 4 : Using String join() method
JDK 8 added a new join() method in String class that can be used to concatenate two or more strings.
Along with the strings to join, it also takes a delimiter that it should add between the strings in result.
String joinedString = String.join(" ", str1, str2); System.out.println(joinedString);
Example program with all the above options
package com.topjavatutorial; public class ProgramStringConcatenation { public static void main(String[] args) { // This program shows multiple ways of concatenating string in java String str1 = "Hello"; String str2 = "World"; //Method 1 : Using + operator String str3 = str1 +" " + str2; System.out.println(str3); //Method 2 : Using concat() method String str4 = str1.concat(" ").concat(str2); System.out.println(str4); //Method 3 : Using StringBuffer or StringBuilder StringBuilder builder = new StringBuilder(); builder.append(str1).append(" ").append(str2); System.out.println(builder.toString()); //Method 4 : Using join() method added in JDK 8 String joinedString = String.join(" ", str1, str2); System.out.println(joinedString); } }
Output :
Hello World
Hello World
Hello World
Hello World
You may also like the following articles:
Performance comparison of different methods of Spring concatenation
© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post
#
#