Leading Zeros in Java: From Beginner to Pro with Performance Measurement
\n\nEvery Java developer sooner or later faces the task: "How to add zeros to the left of a number?" It seems like a trivial operation — take the number 42 and turn it into "000042". But as soon as you start googling, you come across dozens of ways: String.format, DecimalFormat, StringBuilder, manual loops, and even String.repeat (Java 11+).
The question "How can I pad an integer with zeros on the left?" on Stack Overflow has gathered thousands of views. And this is no coincidence. Behind this simple action lies a whole layer of dilemmas: which method is faster? Which is more readable? Which won't kill performance in a high-load application?
\n\nIn this article, we will not just show code. We will conduct our own mini-research, measure the speed of each approach, and give clear recommendations. You will learn when you can sacrifice microseconds for elegance, and when it's better to write "dirty" but lightning-fast code.
\n\nWhy is this important? Performance Context
\n\nSuppose you are generating millions of string identifiers in an ETL process, generating order numbers, or serializing data for logs. Every extra nanosecond spent on padding zeros multiplies by the number of operations. The difference between "beautiful" String.format and manual StringBuilder can be hundreds of percent.
But don't rush to optimize everything. As Donald Knuth said: "Premature optimization is the root of all evil." First, let's understand the tools, and then decide which one to choose.
\n\nMethod 1: String.format() — The King of Readability
\n\nThe most popular and intuitive option. The String.format() method uses the %0Nd specifier, where N is the total length of the resulting string.
int number = 42;\nString padded = String.format("%06d", number); // "000042"\nSystem.out.println(padded);\n\nThe advantages are obvious: the code reads like plain text, no need to think about edge cases. The downside is performance. String.format internally creates a Formatter and parses the format string on every call. For one-off operations — ideal, for a loop of 10 million iterations — questionable.
Method 2: DecimalFormat — Legacy of Currency Formats
\n\nThe DecimalFormat class from the java.text package was originally created for formatting currencies and percentages, but it handles leading zeros perfectly.
import java.text.DecimalFormat;\n\nDecimalFormat df = new DecimalFormat("000000");\nString padded = df.format(42); // "000042"\n\nThe main nuance: DecimalFormat is not thread-safe. If you use it in a multithreaded environment, you'll either have to synchronize or create a new instance for each call (which kills performance).
Method 3: StringBuilder + Manual Calculation — Hardcore
\n\nFor those who aren't afraid to write a couple of extra lines for speed. We create a character array of the required length, fill it with zeros, and then copy the digits of the number from the end.
\n\npublic static String padLeftZeros(int number, int totalLength) {\n char[] result = new char[totalLength];\n for (int i = 0; i < totalLength; i++) {\n result[i] = '0';\n }\n int index = totalLength - 1;\n while (number > 0 && index >= 0) {\n result[index--] = (char) ('0' + (number % 10));\n number /= 10;\n }\n return new String(result);\n}\n\n// Usage:\nString padded = padLeftZeros(42, 6); // "000042"\n\nThis method works many times faster than String.format, but requires care: you need to handle negative numbers (we don't consider them for simplicity) and the case when the number is longer than the specified length.