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?

1
  • you might have problems for strings larger than 8 chars Commented Aug 14, 2015 at 17:28

1 Answer 1

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".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.