Java Print Variables - Complete Guide
Printing Variables in Java
Printing variables is essential for debugging, user interaction, and displaying program results. Java provides multiple ways to output variable values, each with specific advantages.
Choosing the right printing method depends on context, formatting needs, and readability.
Basic Variable Printing Techniques
The simplest approach is concatenating variables with strings using System.out.print or println.
Example
public class PrintVariablesBasic {
public static void main(String[] args) {
String name = "Alice";
int age = 30;
double salary = 75000.50;
boolean isEmployed = true;
char initial = 'A';
// Print variables
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: $" + salary);
System.out.println("Employed: " + isEmployed);
System.out.println("Initial: " + initial);
// Print multiple variables
System.out.println("Employee: " + name + ", Age: " + age + ", Salary: $" + salary);
// Using print (no newline)
System.out.print("Contact: ");
System.out.print(name + " (" + initial + ")");
}
}
Output
Name: Alice Age: 30 Salary: $75000.5 Employed: true Initial: A Employee: Alice, Age: 30, Salary: $75000.5 Contact: Alice (A)
Formatted Output with printf
The printf method allows precise control over formatting and alignment.
Example
public class PrintfVariables {
public static void main(String[] args) {
String product = "Laptop";
double price = 1299.99;
int quantity = 3;
double discount = 0.15;
// Basic formatting
System.out.printf("Product: %s%n", product);
System.out.printf("Price: $%.2f%n", price);
System.out.printf("Quantity: %d%n", quantity);
// Multiple variables
System.out.printf("%s - $%.2f x %d%n", product, price, quantity);
// Column formatting
System.out.printf("%-15s %-10s %-8s%n", "Product", "Price", "Qty");
System.out.printf("%-15s $%-9.2f %-8d%n", "Laptop", 1299.99, 3);
System.out.printf("%-15s $%-9.2f %-8d%n", "Mouse", 49.99, 5);
System.out.printf("%-15s $%-9.2f %-8d%n", "Keyboard", 89.99, 2);
// Calculations in printf
double total = price * quantity;
double discountedTotal = total * (1 - discount);
System.out.printf("Total: $%,.2f%n", total);
System.out.printf("After %.0f%% discount: $%,.2f%n", discount * 100, discountedTotal);
}
}
Output
Product: Laptop Price: $1299.99 Quantity: 3 Laptop - $1299.99 x 3 Product Price Qty Laptop $1299.99 3 Mouse $49.99 5 Keyboard $89.99 2 Total: $3,899.97 After 15% discount: $3,314.97
Advanced Variable Printing Techniques
For localization, efficiency, and structured text, Java provides NumberFormat, StringBuilder, and String.format.
Example
import java.text.NumberFormat;
import java.util.Locale;
public class AdvancedPrinting {
public static void main(String[] args) {
double revenue = 1234567.89;
int customers = 12345;
// NumberFormat for localization
NumberFormat currency = NumberFormat.getCurrencyInstance(Locale.US);
NumberFormat number = NumberFormat.getNumberInstance(Locale.US);
System.out.println("Revenue: " + currency.format(revenue));
System.out.println("Customers: " + number.format(customers));
// StringBuilder for efficiency
StringBuilder sb = new StringBuilder();
sb.append("Monthly Report:\n")
.append("Revenue: ").append(currency.format(revenue)).append("\n")
.append("Customers: ").append(number.format(customers)).append("\n")
.append("Average: ").append(currency.format(revenue / customers));
System.out.println(sb);
// Printing arrays
int[] scores = {85, 92, 78, 90, 88};
System.out.print("Scores: ");
for (int i = 0; i < scores.length; i++) {
System.out.print(scores[i] + (i < scores.length - 1 ? ", " : ""));
}
System.out.println();
// String.format for reusable strings
String report = String.format("Revenue: %s | Customers: %s",
currency.format(revenue),
number.format(customers));
System.out.println(report);
}
}
Output
Revenue: $1,234,567.89 Customers: 12,345 Monthly Report: Revenue: $1,234,567.89 Customers: 12,345 Average: $100.07 Scores: 85, 92, 78, 90, 88 Revenue: $1,234,567.89 | Customers: 12,345
Debugging with Variable Printing
Printing variable values helps trace program flow and debug algorithms. Example: printing intermediate states of sorting.
Example
public class DebugPrinting {
public static void main(String[] args) {
int[] numbers = {5, 2, 8, 1, 9};
System.out.println("Original array: " + java.util.Arrays.toString(numbers));
bubbleSort(numbers);
System.out.println("Sorted array: " + java.util.Arrays.toString(numbers));
}
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
System.out.printf("\nPass %d:%n", i + 1);
System.out.println("Before: " + java.util.Arrays.toString(arr));
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
System.out.printf("Swapped %d and %d%n", arr[j], arr[j + 1]);
}
}
System.out.println("After: " + java.util.Arrays.toString(arr));
}
}
}
Output
Original array: [5, 2, 8, 1, 9] Pass 1: Before: [5, 2, 8, 1, 9] Swapped 2 and 5 Swapped 1 and 8 After: [2, 5, 1, 8, 9] Pass 2: Before: [2, 5, 1, 8, 9] Swapped 1 and 5 After: [2, 1, 5, 8, 9] Pass 3: Before: [2, 1, 5, 8, 9] Swapped 1 and 2 After: [1, 2, 5, 8, 9] Pass 4: Before: [1, 2, 5, 8, 9] After: [1, 2, 5, 8, 9] Sorted array: [1, 2, 5, 8, 9]