In this part of tutorial we will learn java string concatenation. So when we have to add up two String’s and print to gether we use this concept.
Java String Concatenation :
Now String’s are not an integer to add up directly but the concept is to print them together.
Lets see the way’s to do so.
- ‘+’ operator
- String Buffer
- String Builder
- concat method -> concat()
‘+’ operator
We consider two String to be added
// + operator String a = "abc"; String b = "def";
now we can combine them to form a single String ‘res’.
String res = a+" "+b;
// + operator String a = "abc"; String b = "def"; String res = a+" "+b; System.out.println(res);
String Buffer:
String Buffer is a mutable String i.e., it can modified later on.When you try to concat two String’s using String it much slower and also memory will be more consumed because every time you need to recreate a String variable.
With append method you can add two Strings and store it in a Buffer
// String Buffer StringBuffer sb = new StringBuffer(15); sb.append("String").append(" ").append("Buffer"); System.out.println(sb.toString());
String Builder:
String Builder is a mutable String i.e., it can modified later on.When you try to concat two String’s using String it much slower and also memory will be more consumed because every time you need to recreate a String variable.
With append method you can add two Strings and store it in a String Builder.
// String Builder StringBuilder sb = new StringBuilder(14); sb.append("String") .append(" ") .append("Builder"); System.out.println(sb.toString());
concat():
The concat method in java concatenates one String to the another String.
// Concat String s1 = "android "; String s2 = "coding.in"; String s3 = s1.concat(s2); System.out.println(s3);
If any query’s on Java String Concatenation let us know in the comment section below.
For more interesting tutorials do like and share this tutorial.