Difference between concat and append in Java

Difference between concat and append in Java

Difference between concat and append in java:

concat():

  • String has concat method, remember string is immutable.
  • It adds a string to another string.
  • It will create the new object after concatenation done, since it is a immutable.

append():

  • StringBuilder and StringBuffer has append method, remember these two are mutable.
  • It appends a char or char sequence to a string.
  • It will not create a new object, since it is a mutable one.

Example Program:

package com.ngdeveloper.com;

public class StringConcatenation {

public static void main(String[] args) {
//Concatenating string with another string
String helloVariable = "hello ";
String worldVariable = "world";
System.out.println(helloVariable.concat(worldVariable)); //hello world

//Appending string to string
StringBuilder helloStrBuilderVariable = new StringBuilder("hello");
StringBuilder worldStrBuilderVariable = new StringBuilder(" world");
System.out.println(helloStrBuilderVariable.append(worldStrBuilderVariable)); //prints hello world

//Appending char to string
StringBuilder charVariable = new StringBuilder("Java");
System.out.println(charVariable.append('D')); // prints JavaD

}

}

 

Output:
hello world
hello world
JavaD

[/sociallocker]

 

 

Must Know Differences in Java:

String vs StringBuilder vs StringBuffer Difference

Difference between equals() and == ?

Hashset vs LinkedHashSet vs TreeSet Difference

Difference between HashMap vs LinkedHashMap

7,078 total views, 1 views today

One thought on “Difference between concat and append in Java

  1. StringBuffer is synchronized as well as Thread safe so can be used in multithreading. StringBuilder is not synchronized as well as thread safe. Many thanks for sharing this.

Leave a Reply

Your email address will not be published. Required fields are marked *