Explain Codes LogoExplain Codes Logo

Sprintf equivalent in Java

java
string-formatting
java-8
string-manipulation
Alex KataevbyAlex Kataev·Oct 27, 2024
TLDR

Use String.format() for a formatted string or System.out.printf() for formatted console output, resembling C's sprintf.

Example with String.format():

String result = String.format("Hey %s, your score is: %d", "Alice", 85);

For System.out.printf():

System.out.printf("Hey %s, your score is: %d%n", "Alice", 85);

Both techniques yield Hey Alice, your score is: 85, with %s for strings and %d for integers.

Mastering string formatting

Understanding place markers

Java employs %, along with a format specifier, to indicate places in the string which will be replaced by variable values. Here are some common specifiers (a.k.a placeholders):

  • %d for integers
  • %f for floating-point numbers
  • %s for strings
  • %x or %X for hexadecimal numbers

Formatting Alignment

You can adjust the alignment and padding of your string. Here's an idea — add numbers between % and the format specifier:

// Add some floor to the Integer String.format("%4d", 42); // " 42"

Quick formatted method

From Java 13, we have a neat formatted method for quick string formatting:

String greeting = "Hello, %s!".formatted("World"); // "Hello, World!"

Complex Formatting Techniques

Power of ByteArrayOutputStream & PrintStream

For complex tasks, Java enables the combination of a PrintStream with a ByteArrayOutputStream. (Feel the power? Good!)

ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); ps.printf("%4d %6.2f", 42, 3.14159); // [Joke: Are we speaking Alien language? ;)] ps.flush(); String formatted = baos.toString(); // The result? A pretty " 42 3.14"

Performance Tricks

Don't stress out your strings! For frequent string manipulation, prefer using StringBuilder over + for concatenation. (Your CPU will thank you!)

StringBuilder hexBuilder = new StringBuilder(); for(byte b : byteArray) { hexBuilder.append(String.format("%02X", b)); // [Joke: Here, take some Hexa!] } String hexString = hexBuilder.toString();

Practical use-cases and tips

Date and Time Formatting

DateTimeFormatter is a perfect choice when dealing with dates and times.

LocalDateTime now = LocalDateTime.now(); String formattedDate = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); // Date Night Ready!

Locale-wise formatting

Locale-specific formatting can keep you from absurd conversions:

String numberString = String.format(Locale.GERMANY, "%,d", 1234567); // "1.234.567", because Germans do it differently!

Efficient Conversion to Hex

A quick lookup table trick for hex conversion can save you a lot of time:

final char[] hexChars = "0123456789ABCDEF".toCharArray(); char[] hex = new char[byteArray.length * 2]; for (int i = 0; i < byteArray.length; i++) { int v = byteArray[i] & 0xFF; hex[i * 2] = hexChars[v >>> 4]; // [Joke: Hex a done. Literally!] hex[i * 2 + 1] = hexChars[v & 0x0F]; } String hexString = new String(hex);