Java String Concatenation – Java example

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.

  1. ‘+’ operator
  2. String Buffer
  3. String Builder
  4. 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);

Java String Concatenation

 

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());

 

Java String Concatenation

 

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());

 

Java String Concatenation

 

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);

 

Java String Concatenation

 

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.

 

Show Buttons
Hide Buttons
Read previous post:
Java Global Variables: A Comprehensive Example in Java Programming

In a previous tutorial, we explored the concept of variables. Now, let's delve into the realm of java global variables...

Close