String Concatenation in Java

String Concatenation in Java: String Concatenation in Java can be possible by two ways,

  • Using + operator.
  • Using Concat() Function.

Example Program:


public class StringConcatenation {

	public static void main(String[] args) {
		String hVariable = "hello ";
		String wVariable = "world";
		String hwVariable = hVariable.concat(wVariable);

		String a = "java";
		String b = "domain";
		String javadomain = a + b;

		System.out.println("String concatenation using concat() : "+hwVariable);
		System.out.println("String concatenation using + operator : "+javadomain);


String concatenation using concat() : hello world
String concatenation using + operator : javadomain

Difference between + and concat():

Using + operator:

1. Any type of variable can be concatenated, it is not mandatory to be a string variable.

		String firstVar = "Java";
		int secVar = 11;
		String plusConcat = firstVar + secVar;
		System.out.println(plusConcat); // prints Java11

2. String can be null and it will not throw null pointer exception.

 String myVar = null;
 String plus = myVar + "java";
 System.out.println(plus); // prints nulljava

Using Concat():

1. Argument must be string for concatenation using concat()

a.concat(11) //it is not possible

2. String must not be null, if it is null then it will throw null pointer exception.

String myVar = null;
String value = "java";
System.out.println(myVar.concat(value)); // throws null pointer exception

343 total views, 1 views today

Leave a Reply

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