- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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. | Key | concat method | + operator |
---|---|---|---|
1 | Type | As 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. |
2 | Number of arguments | The 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. |
3 | Type of input | The 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. |
4 | Output as a new string | The 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. |
5 | Exception during execution | Concat 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. |
6 | Performance | In 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
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
Advertisements
To Continue Learning Please Login
Login with Google