• Home
  • How do you concatenate strings and create format strings?

How do you concatenate strings and create format strings?

In Java, there are several ways to concatenate strings and create formatted strings.

One way to concatenate strings is to use the + operator. For example:

String str1 = "Hello";
String str2 = "World";

String str3 = str1 + " " + str2; // Concatenates str1, a space, and str2
System.out.println(str3); // Prints "Hello World"

You can also use the String.concat() method to concatenate strings. For example:

String str1 = "Hello";
String str2 = "World";

String str3 = str1.concat(" ").concat(str2); // Concatenates str1, a space, and str2
System.out.println(str3); // Prints "Hello World"

To create formatted strings, you can use the String.format() method and include placeholders in the string for the values you want to insert. For example:

int num = 123;
String str = String.format("The number is %d", num); // Inserts the value of num into the placeholder %d
System.out.println(str); // Prints "The number is 123"

You can also use the printf() method to create formatted strings. This method works similar to System.out.println(), but allows you to include placeholders in the string for the values you want to insert. For example:

int num = 123;
System.out.printf("The number is %d", num); // Inserts the value of num into the placeholder %d