1

I would like to know what is the meaning of "%0" and "d%s" in java when formatting a string.

String.format("%0"+ (8 - "Apple".length() )+"d%s",0 ,"Apple"); 

Output:

000Apple

I was searching for a way to format a string with leading zeros, and that code does the work, but I don't know why it works.

Found that line of code here:
How to format a Java string with leading zero?

Community
  • 1
  • 1
myProfile
  • 23
  • 1
  • 1
  • 3

1 Answers1

12

%d means number. %0nd means zero-padded number with a length.

You build n by subtraction in your example.

%s is a string.

Your format string ends up being this:

"%03d%s", 0, "Apple"

So you print a zero-padded 0 that's three digits long, and the string "Apple".

Dave Newton
  • 158,873
  • 26
  • 254
  • 302