combine strings java code example

Example 1: java concatenate strings

public class Concat {
    String cat(String a, String b) {
        a += b;
        return a;
    }
}

Example 2: java best way to concatenate strings

// StringBuilder
String stringBuilderConcat = new StringBuilder()
    .append(greeting)
    .append(" ")
    .append(person)
    .append("! Welcome to the ")
    .append(location)
    .append("!")
    .build();

Example 3: how do you combine 2 strings in java

-By  using (+) operator
-By  using concatenate method (concat()).
                      String strconcat3=strconcat2.concat(strconcat);

-By StringBuffer
-String strconcat= new StringBuilder().append("matt")
                                .append("damon").toString();
                                
-By StringBuilder
- String strconcat2= new StringBuffer()
                  .append("matt").append("damon").toString();

Example 4: how to add strings together

String firstName = "BarackObama";
String lastName = " Care";
//First way
System.out.println(firstName + lastName);
//Second way
String name = firstName + lastName;
System.out.println(name);
//Third way
System.out.println("BarackObama" + " Care");