Avatar ·

How to add leading zeros to an integer in Java?

Hello everyone! I'm a beginner Java developer and I've encountered a task: I need to output a number with leading zeros on the left so that it always takes up a certain number of characters. For example, the number 5 should become "0005", and 123 should become "0123" (so that the string length is 4 characters).

\n\n

I tried using string concatenation and loops, but it looks terrible and inconvenient. Here's my current code:

\n\n
int number = 5;\nString result = "";\nif (number < 10) {\n    result = "000" + number;\n} else if (number < 100) {\n    result = "00" + number;\n} else if (number < 1000) {\n    result = "0" + number;\n} else {\n    result = String.valueOf(number);\n}\nSystem.out.println(result); // Outputs "0005"\n
\n\n

This code only works for numbers up to 9999 and looks