Java का printf और format
In this page:
System.out.printf("format %s %d %.2f%n", stringValue, intValue, doubleValue);
Basic printf Syntax
printf() %s (string) और %d (integer) जैसे placeholders वाली एक format string लेता है, फिर print करते समय आपके arguments को उन placeholders में order में substitute करता है।
उदाहरण: Basic printf Syntax
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
// Print formatted text to the console
System.out.printf("%s is %d years old%n", "Alice", 30);
}
}
Login to try C/C++/Java/PHP code in the editor
Formatting Decimals
%f specifier floating-point numbers print करता है, और %.2f जैसी एक precision जोड़ना decimal point के बाद exactly दो digits round और display करता है -- currency या measurements को consistently format करने के लिए handy।
उदाहरण: Formatting Decimals
public class Main {
public static void main(String[] args) {
System.out.printf("%.2f%n", 19.999); // rounds to exactly 2 decimal places
}
}
Login to try C/C++/Java/PHP code in the editor
Width and Alignment
Conversion character से पहले एक number रखना, जैसे %10d, output को कम से कम उतने characters चौड़ा pad करता है; उस width को minus sign से prefix करना, %-10d, इसके बजाय इसे left-align करता है default right-alignment के बजाय।
उदाहरण: Width and Alignment
public class Main {
public static void main(String[] args) {
System.out.printf("[%10d]%n", 42); // right-aligned, padded to width 10
System.out.printf("[%-10d]%n", 42); // left-aligned instead
}
}
Login to try C/C++/Java/PHP code in the editor
Printing Multiple Variables
पहले से आगे extra arguments left से right placeholders से match होते हैं, इसलिए printf("%s is %d", name, age) को उस order में बिल्कुल एक String और एक int argument चाहिए नहीं तो आपको एक runtime format exception मिलेगी।
उदाहरण: Printing Multiple Variables
public class Main {
public static void main(String[] args) {
String name = "Bob";
int age = 25;
System.out.printf("%s is %d%n", name, age); // matched left to right
}
}
Login to try C/C++/Java/PHP code in the editor
System.out.format()
System.out.format() PrintStream पर defined printf() का एक plain alias है -- दोनों identical format syntax और arguments accept करते हैं, इसलिए आप किसे call करते हैं यह विशुद्ध रूप से personal style की बात है।
उदाहरण: System.out.format()
public class Main {
public static void main(String[] args) {
System.out.format("%s scored %d%n", "Sam", 95); // format() is an alias for printf()
}
}
Login to try C/C++/Java/PHP code in the editor
- गलत format specifier उपयोग करना, जैसे एक
doubleके लिए%d, जोIllegalFormatConversionExceptionthrow करता है। printfके साथ\nया%nभूल जाना, क्योंकि यह खुद से नई line नहीं जोड़ता।- बहुत कम arguments pass करना, जो
MissingFormatArgumentExceptionthrow करता है।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: