Difference between concat() and + operator in Java


Java provides two ways in order to append strings and make them one. These two methods are namely Concat() method and + operator. Both are developed for the same functionality but still have some major differences.

The following are the important differences between concat method and + operator.

Sr. No.Keyconcat method+ operator
1TypeAs syntax refers concat() is a method and comes under java.lang.String package.While on the other hand + is an operator and not a method.
2Number of argumentsThe concat method could take the only argument as input and append this input to the target string on which this method is called.+ operator could append any number of strings and it not bouded to only input as a parameter.
3Type of inputThe concat method could only take string as input and would ask for compile time error if any other type of input has been provided to it.+ operator could take any type of input and convert it to a string before append to the target string.
4Output as a new stringThe concat method would create new string object as output after appending only if output string has length greater than zero otherwise return the same target string as an output object.+ operator always create new object as output no matter what length of result string produced after appending.
5Exception during executionConcat method returns null pointer exception in case this method called with null as input.+ operator on the other hand do not throw any exception in a case called with null.
6PerformanceIn the case of concat method as no new object is created if result string is of zero length hence it consumes lesser memory as compared to + operator.While + operator always create a new object in the memory while appending the strings hence consumes more memory.

Example of concat method vs + operator

ConcatDemo.java

public class ConcatDemo {
   public static void main(String args[]){
      String s = "I am ";
      s = s.concat("Indian");
      System.out.println(s);
   }
}

Output

I am Indian

Example

 Live Demo

OperatorDemo.java

public class OperatorDemo {
   public static void main(String args[]){
      String s1 = "I am ";
      String s2 = "Indian";
      String s3 = s2 + s1;
      System.out.println(s3);
   }
}

Output

Indian I am

Updated on: 18-Sep-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements