Is it possible to format string like 05 if input was 5 (one literal)?
System.out.println(String.format("%d", 5)); //it should be 05
System.out.println(String.format("%d", 15)); //15
>Solution :
Yes, you can achieve this by using the %02d format specifier in String.format(). The 0 indicates that you want to pad with zeros, and the 2 specifies the minimum width, ensuring that there are at least two characters. If the number has only one digit, it will be padded with a leading zero.
Here’s how you can use it:
System.out.println(String.format("%02d", 5)); // Outputs: 05
System.out.println(String.format("%02d", 15)); // Outputs: 15
In this example, %02d ensures that the output is at least two digits, padding with zeros if necessary.