Java String format Example

Sameera De Silva
2 min readJun 5, 2024

--

Imagine a situation where, that you need to use parameize text. So, in that case you could use String.format Method.

String.format Method:

String.format is a static method in the String class used for string formatting.
It takes a format string as the first argument and optional arguments containing the values to be inserted.

To store the parameter value we use Format specifier

Format specifier act like placeholders that get replaced with the actual values you provide.
A format specifier always starts with a percent sign (%).
Following the percent sign is a character indicating the data type to be formatted.

Format Specifiers:

  • %s - String
  • %d - Decimal integer
  • %f - Floating point
  • %x - Hexadecimal integer
  • %t - Date/Time
package com.test.testcases;

import org.testng.annotations.Test;

public class StringFormatDemo {

String prefix = "Call up to " ;

String iddMinutes="666";

int value =12;

String suffix = " mins / mo across Australia, Bangladesh, Brunei, Canada";

String messageTemplate = "Call up to %s mins/month across 25 countries: Bangladesh, Canada, China";


@Test
public void formatText(){
String descriptionWithThreeString = String.format("%s%s%s", prefix, iddMinutes, suffix);
System.out.println(descriptionWithThreeString);

// Using String.format to concatenate the prefix, iddMinutes, and suffix
String descriptionWithStringIntString = String.format("%s%d%s", prefix, value, suffix);
System.out.println(descriptionWithStringIntString);

// Using String.format to replace the placeholder with iddMinutes
String message = String.format(messageTemplate, iddMinutes);

// Printing the formatted message
System.out.println(message);
}
}

output

Call up to 666 mins / mo across Australia, Bangladesh, Brunei, Canada
Call up to 12 mins / mo across Australia, Bangladesh, Brunei, Canada
Call up to 666 mins/month across 25 countries: Bangladesh, Canada, China

Another example-

package com.test.testcases;

import org.testng.annotations.Test;

public class Temp {

String iddMinutes = "666";
String messageTemplate = "Call up to %s mins/mo across 15 countries";

@Test
public void formatText() {
// Using String.format to replace the placeholder with iddMinutes
String expectedLongDescription = String.format(messageTemplate, iddMinutes);

// Printing the formatted message
System.out.println(expectedLongDescription);
}
}

Output

Call up to 666 mins/mo across 15 countries

--

--

No responses yet