Difference between concat and + in java

(Last Updated On: August 11, 2016)

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

186 total views, 1 views today

Leave a Reply

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