Difference between concat and append in java:
In core java, its difficult to write a meaningful program without string data type. StringBuffer and StringBuilder’s are different variations of the String for different purpose in java.
But we as a java developer, needs to use concat() for string and append() for stringbuilder and stringbuffer. Knowing the difference between these two makes us a good quality developer, as this will help us to use the best one at the right use cases.
Table of Contents
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.
Concat() Java Sample Program:
package com.ngdeveloper; public class StringConcat { 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 } }
Concat() Java Sample Output:
hello world
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.
append() Java sample Program:
package com.ngdeveloper; public class StringBufferBuilderAppend { public static void main(String[] args) { //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("Ng"); System.out.println(charVariable.append('Developer')); // prints JavaD } }
append() Java Sample Output:
NgDeveloper
Difference between concat and append Java Program:
package com.ngdeveloper; 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