Concatenation:


Concatenation is the process of combining two or more strings to create a new string.

In Java, the + operator and the concat() method are commonly used for string concatenation.

Example using the + operator:


String firstName = "John";
String lastName = "Doe";
String fullName = firstName + " " + lastName; 
System.out.println(fullName); // Output: John Doe

In the above example, the + operator concatenates the firstName, space character, and lastName strings, creating a new string fullName with the value "John Doe".


Example using the concat() method:


String str1 = "Hello"
String str2 = "World";
String message = str1.concat(" ").concat(str2); 
System.out.println(message); // Output: Hello World

In this example, the concat() method is used to concatenate the str1, space character, and str2 strings together. The resulting string message contains the value "Hello World".


Note: It's worth mentioning that string concatenation in Java can also be performed efficiently using StringBuilder or StringBuffer classes, especially when concatenating multiple strings within a loop or performance-critical scenarios.


It's important to understand and utilize string concatenation effectively to build new strings from existing ones, whether it's through the + operator or the concat() method. 

This allows for flexible string manipulation and building dynamic content in your Java programs.


Difference between + and concat() In String?