Java Multiple Variables - Complete Guide
Working with Multiple Variables
Java provides several ways to declare, initialize, and work with multiple variables at once. Using these approaches helps write cleaner, more concise code and improves readability.
Managing multiple variables effectively is important for handling related data, performing batch operations, and keeping programs organized.
Declaring Multiple Variables
You can declare multiple variables of the same type in one statement. This reduces redundancy but should be used carefully for readability.
public class MultipleVariablesDeclaration {
public static void main(String[] args) {
// Declaration only
int x, y, z;
double price, discount, total;
String firstName, lastName, email;
// Initialization separately
x = 10;
y = 20;
z = 30;
price = 100.0;
discount = 0.1;
total = price - (price * discount);
firstName = "John";
lastName = "Doe";
email = "john.doe@example.com";
// Declaration and initialization in one line
int a = 5, b = 10, c = 15;
double width = 10.5, height = 20.3, depth = 15.2;
String city = "New York", state = "NY", country = "USA";
// Mixed declaration (less readable)
int i = 1, j, k = 3;
j = 2;
System.out.println("Coordinates: (" + x + ", " + y + ", " + z + ")");
System.out.println("Price: $" + price + ", Discount: " + discount + ", Total: $" + total);
System.out.println("Name: " + firstName + " " + lastName + ", Email: " + email);
}
}
Coordinates: (10, 20, 30) Price: $100.0, Discount: 0.1, Total: $90.0 Name: John Doe, Email: john.doe@example.com
Variable Groups and Related Data
Grouping related variables makes the code more maintainable and clear. For example, separate groups can represent personal info, address, or order details.
public class VariableGroups {
public static void main(String[] args) {
// Personal information
String personName = "Alice Smith";
int personAge = 28;
String personEmail = "alice.smith@email.com";
String personPhone = "555-1234";
// Address information
String street = "123 Main St";
String city = "Boston";
String state = "MA";
String zipCode = "02108";
// Order information
String orderId = "ORD-12345";
String productName = "Java Programming Book";
int quantity = 2;
double unitPrice = 49.99;
double orderTotal = quantity * unitPrice;
System.out.println("=== PERSONAL INFORMATION ===");
System.out.println("Name: " + personName);
System.out.println("Age: " + personAge);
System.out.println("Email: " + personEmail);
System.out.println("Phone: " + personPhone);
System.out.println("\n=== ADDRESS INFORMATION ===");
System.out.println("Street: " + street);
System.out.println("City: " + city);
System.out.println("State: " + state);
System.out.println("ZIP: " + zipCode);
System.out.println("\n=== ORDER INFORMATION ===");
System.out.println("Order ID: " + orderId);
System.out.println("Product: " + productName);
System.out.println("Quantity: " + quantity);
System.out.println("Unit Price: $" + unitPrice);
System.out.println("Total: $" + orderTotal);
}
}
=== PERSONAL INFORMATION === Name: Alice Smith Age: 28 Email: alice.smith@email.com Phone: 555-1234 === ADDRESS INFORMATION === Street: 123 Main St City: Boston State: MA ZIP: 02108 === ORDER INFORMATION === Order ID: ORD-12345 Product: Java Programming Book Quantity: 2 Unit Price: $49.99 Total: $99.98
Working with Variable Arrays
For larger sets of similar variables, arrays provide a structured and scalable solution instead of creating many separate variables.
public class VariableArrays {
public static void main(String[] args) {
// Instead of separate variables
int[] scores = {85, 92, 78, 90, 88};
String[] names = {"Alice", "Bob", "Charlie", "Diana", "Eve"};
double[] prices = {19.99, 29.99, 9.99, 49.99, 14.99};
int totalScore = 0;
double totalValue = 0.0;
System.out.println("=== STUDENT SCORES ===");
for (int i = 0; i < scores.length; i++) {
System.out.printf("%-8s: %d%n", names[i], scores[i]);
totalScore += scores[i];
}
System.out.println("\n=== PRODUCT PRICES ===");
for (int i = 0; i < prices.length; i++) {
System.out.printf("Product %d: $%.2f%n", i + 1, prices[i]);
totalValue += prices[i];
}
double averageScore = (double) totalScore / scores.length;
System.out.printf("\nAverage Score: %.1f%n", averageScore);
System.out.printf("Total Value: $%.2f%n", totalValue);
// Multi-dimensional array for employees
String[][] employees = {
{"John", "Doe", "Developer", "50000"},
{"Jane", "Smith", "Designer", "45000"},
{"Bob", "Johnson", "Manager", "60000"}
};
System.out.println("\n=== EMPLOYEE DATA ===");
for (String[] employee : employees) {
System.out.printf("%-10s %-10s %-12s $%s%n",
employee[0], employee[1], employee[2], employee[3]);
}
}
}
=== STUDENT SCORES === Alice : 85 Bob : 92 Charlie : 78 Diana : 90 Eve : 88 === PRODUCT PRICES === Product 1: $19.99 Product 2: $29.99 Product 3: $9.99 Product 4: $49.99 Product 5: $14.99 Average Score: 86.6 Total Value: $124.95 === EMPLOYEE DATA === John Doe Developer $50000 Jane Smith Designer $45000 Bob Johnson Manager $60000
Variable Swapping and Manipulation
Operations on multiple variables often involve swapping values or performing batch updates. Java provides straightforward approaches using temporary variables, arrays, or loops.
public class VariableOperations {
public static void main(String[] args) {
// Swapping two variables
int a = 5, b = 10;
System.out.println("Before swap: a = " + a + ", b = " + b);
int temp = a;
a = b;
b = temp;
System.out.println("After swap: a = " + a + ", b = " + b);
// Rotating multiple variables
int x = 1, y = 2, z = 3, w = 4;
System.out.println("Before rotation: x=" + x + ", y=" + y + ", z=" + z + ", w=" + w);
temp = w;
w = z;
z = y;
y = x;
x = temp;
System.out.println("After rotation: x=" + x + ", y=" + y + ", z=" + z + ", w=" + w);
// Applying discount to multiple variables
double price1 = 19.99, price2 = 29.99, price3 = 39.99;
double discount = 0.2;
price1 *= (1 - discount);
price2 *= (1 - discount);
price3 *= (1 - discount);
System.out.println("\nDiscounted Prices:");
System.out.printf("Price 1: $%.2f%n", price1);
System.out.printf("Price 2: $%.2f%n", price2);
System.out.printf("Price 3: $%.2f%n", price3);
// Using an array for batch updates
double[] prices = {19.99, 29.99, 39.99};
for (int i = 0; i < prices.length; i++) {
prices[i] *= (1 - discount);
}
System.out.println("\nArray Discounted Prices:");
for (double price : prices) {
System.out.printf("$%.2f%n", price);
}
}
}
Before swap: a = 5, b = 10 After swap: a = 10, b = 5 Before rotation: x=1, y=2, z=3, w=4 After rotation: x=4, y=1, z=2, w=3 Discounted Prices: Price 1: $15.99 Price 2: $23.99 Price 3: $31.99 Array Discounted Prices: $15.99 $23.99 $31.99