Trying to understand System.out.printf
Formatting java strings with system.out.printf - Stack Overflow
java - System.out.printf vs System.out.format - Stack Overflow
java - What does System.out.printf( "%-15sd\n", s1, x) do? - Stack Overflow
Videos
What are the arguments you can use for it? How is it used? How does it differ from other print methods. Looks like there might different operators it uses to. I'm new so excuse my ignorance. :)
System.out is a PrintStream, and quoting the javadoc for PrintStream.printf
An invocation of this method of the form
out.printf(l, format, args)behaves in exactly the same way as the invocationout.format(l, format, args)
The actual implementation of both printf overloaded forms
public PrintStream printf(Locale l, String format, Object ... args) {
return format(l, format, args);
}
and
public PrintStream printf(String format, Object ... args) {
return format(format, args);
}
uses the format method's overloaded forms
public PrintStream format(Locale l, String format, Object ... args)
and
public PrintStream format(String format, Object ... args)
respectively.
This is Java's formatter syntax. You can find more about it here. In your case, you have 2 parameters, that get formatted.
First s1 which is formatted using %-15s. The % means that what follows is an argument that will be formatted. Then follows a - resulting in left alignment. 15 fills the string up to a length of 15 characters (adding spaces at the end). Finally the s means, that you are formatting a string.
Second x which is formatted using %03d. Here the 0 is the fill character, meaning that, if necessary, zeros are added. The 3 is again the width, meaning the fill character 0 is added as many times as necessary to make it 3 digits long (this time at the beginning). Finally d means, that a integer is formatted.
"%-15s" means that within 15 blank space, the String "s1" will be filled in the left. (fill in the blanks from the left) "%03d" means that within 3 0s, the integer"x" will be filled in the right.(fill in the zeros from the right).
This can only be done by using printf method.