It’s used to print formatted strings using various format specifiers.
‘Format specifiers’를 사용해 formatted된 String을 출력하는 데 사용된다.
printf() method is not only there in C, but also in Java. printf() 메소드는 C에만 있는 것이 아니라, Java에도 있다.Syntax
System.out.printf(format, arguments);
System.out.printf(locale, format, arguments);
System.out.printf()과 String.format()의 차이?
Let’s look at the available format specifiers available for printf:
printf()The conversion-character is required and determines how the argument is formatted.
s formants strings.
d formats decimal integers.
f formats floating-point numbers.
t formats date/time values.
To break the string into separate lines, we have a %n specitife.
To format Boolean values, we use the %b format.
public class Main2 {
public static void main(String[] args) {
System.out.printf("%b%n", null);
System.out.printf("%B%n", false);
System.out.printf("%b%n", 5.3);
System.out.printf("%B%n", "random text");
}
}
Example
public class Main {
public static void main(String[] args) {
System.out.printf("%d This is a format string",123 );
boolean myBoolean = true;
char myChar = '@';
String myString = "Bro";
int myInt = 50;
double myDouble = 1000;
System.out.printf("%b", myBoolean);
System.out.printf("%c ", myChar);
System.out.printf("%s", myString);
System.out.printf("%d", myInt);
}
}
Example
package printf;
public class Main {
public static void main(String[] args) {
System.out.printf("%d This is a format string",123 );
boolean myBoolean = true;
char myChar = '@';
String myString = "Bro";
int myInt = 50;
double myDouble = 1000;
[conversion-character]
System.out.printf("%b", myBoolean);
System.out.printf("%c ", myChar);
System.out.printf("%s", myString);
System.out.printf("%d", myInt);
[width]
minimum number of characters to be written as output
System.out.printf("Hello %-10s", myString);
[precision]
sets number of digits of precision when outputting floating-point values
System.out.printf("You have this much money %.1f", myDouble );
System.out.printf("You have this much money %f", myDouble );
[flags]
adds an effect to output based on the flag added to format specifier
- : left-justify, +:output a plus(+) or minus (-) sign for a numeric values
0 : numeric values are zero-paded
, : comma grouping separator if numbers > 1000
System.out.printf("You have this much money %,f", myDouble );
}
}