Multiple Variable Declaration
You'll learn how to declare several variables of the same type in one line, and when it's a good idea.
The Core Idea
Java allows you to declare multiple variables of the same type in a single statement by separating them with commas. Instead of writing separate declaration lines, you can group them together—but this convenience comes with readability tradeoffs.
Basic Syntax
Here's the pattern:
int x, y, z;
This declares three int variables: x, y, and z. It's equivalent to:
int x;
int y;
int z;
You can also initialize some or all variables in the same statement:
int a = 5, b = 10, c = 15;
int m = 1, n, p = 3; // n is declared but uninitialized
The Readability Question
While compact, multiple declarations can reduce clarity:
Less readable:
double price, tax, total, discount, finalAmount;
More readable:
double price;
double tax;
double total;
double discount;
double finalAmount;
The second approach makes it easier to spot each variable and add comments if needed. When variables serve different purposes, separate declarations often communicate intent better.
When to Use It
Multiple declaration works well for closely related variables:
int width, height; // screen dimensions
char first, middle, last; // name initials
Key Takeaway: You can declare multiple variables of the same type in one line using commas, but favor clarity over brevity—separate declarations are often easier to read and maintain, especially for beginners.