Difference between concat and + in java

Difference between + and concat():

Using + operator:

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

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

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

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

  

Using Concat():

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

[java]
a.concat(11) //it is not possible
[/java]

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

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

Leave a Reply