Mina Michael Mina Michael - 17 days ago 5
Java Question

What is "%8s" in String.format() in java?

I was trying to print out a byte as a binary string without its sign. I followed this answer:

String.format("%8s", Integer.toBinaryString(byteVariable & 0xFF)).replace(' ', '0');


but I don't understand the role of
"%8s"





I thought it's to choose a number of characters from the string, but I tried:

System.out.println(String.format("%8s", "asdfasdfasdfasdf"));


and it prints
asdfasdfasdfasdf
as it it, not
asdfasdf
as I expected.

Answer

The Format String Syntax is:

%[argument_index$][flags][width][.precision]conversion

Your query:

String.format("%8s", Integer.toBinaryString(byteVariable & 0xFF)).replace(' ', '0');

In this case, 8 is the width and s is the conversion.

The width is a non-negative decimal integer indicating the minimum number of characters to be written to the output.

Comments