Join or concatenate or combine multiple strings in java (example)

1. Different methods to join or concatenate strings in java

  1. Join String using + operator
  2. Combine String using String concat method
  3. Contact String using String format
  4. Join String using StringBuilder format
  5. Join String using String join (Method included in java in JDK 1.8)

We have already discussed Join Strings in java8 using StringJoiner.

2. Program –  Join or concat or combine multiple strings in java

package org.learn;

public class JoinStrings {

	public static void main(String[] args) {

		String player = "Maria";
		String game = "Tennis";
		
		// 1. Join String using + operator
		System.out.println("1 Join String using + operator:");
		String playerAndGame = player + game;		
		System.out.println(playerAndGame);
		playerAndGame = player + " " + game;
		System.out.println(playerAndGame);

		// 2. Join String using String concat method
		System.out.println("2. Join String using concat: ");
		playerAndGame = player.concat(game);		
		System.out.println(playerAndGame);
		playerAndGame = player.concat(" ").concat(game);
		System.out.println(playerAndGame);

		// 3. Join String using String format
		System.out.println("3. Join String using String format: ");
		playerAndGame = String.format("%s %s", player, game);
		System.out.println(playerAndGame);

		// 4. Join String using StringBuilder format
		System.out.println("4. Join String using StringBuilder: ");
		StringBuilder builder = new StringBuilder();
		builder.append(player);
		builder.append(" ");
		builder.append(game);
		System.out.println(builder.toString());

		// 5. Join String using String join
		System.out.println("5. Join String using String join: ");
		playerAndGame = String.join(" ", player,game);
		System.out.println(playerAndGame);
	}
}

3. Output – Join or concatenate or combine multiple strings in java

1 Join String using + operator:
MariaTennis
Maria Tennis
2. Join String using concat: 
MariaTennis
Maria Tennis
3. Join String using String format: 
Maria Tennis
4. Join String using StringBuilder: 
Maria Tennis
5. Join String using String join: 
Maria Tennis
Scroll to Top