ตัวอย่าง: พิมพ์ตัวแปรหลายแบบ
public class Demo {
public static void main(String[] args) {
String firstName = "Hello";
String lastName = "World";
// 1. println - เรียบง่าย
System.out.println("Printing single variable");
System.out.println(firstName);
// 2. printf - จัดรูปแบบ (format string)
System.out.println("\nPrinting multiple variables with printf");
System.out.printf("First Name: %s%nLast Name: %s%n", firstName, lastName);
// 3. String.format - สร้างสตริง formatted
String formatted = String.format("Name: %s %s", firstName, lastName);
System.out.println("\nUsing String.format: " + formatted);
// 4. ตัวเลขและ formatting
int num = 42;
double pi = 3.14159;
System.out.printf("Number: %d, Pi: %.2f, Hex: %x%n", num, pi, num);
}
}
ผลลัพธ์
Printing single variable
Hello
Printing multiple variables with printf
First Name: Hello
Last Name: World
Using String.format: Name: Hello World
Number: 42, Pi: 3.14, Hex: 2a
Format Specifiers พื้นฐาน
| Specifier | คำอธิบาย | ตัวอย่าง |
| %s | String | "Hello" |
| %d | Integer (decimal) | 42 |
| %f | Floating point | 3.14159 |
| %.2f | Float 2 ตำแหน่งทศนิยม | 3.14 |
| %x | Hexadecimal (lowercase) | 2a |
| %n | Newline (platform-independent) | - |
| %b | Boolean | true/false |
แนวทางเลือก
- พิมพ์ง่ายๆ:
System.out.println() หรือ System.out.print()
- ต้องจัดรูปแบบ:
System.out.printf() หรือ String.format()
- ประสิทธิภาพ:
StringBuilder + append() สำหรับต่อสตริงมาก