Multiple Variables

3 min read ·

In Java, you can declare multiple variables in a single line if they belong to the same data type. This makes the code shorter and cleaner when used properly.
Let’s understand all possible ways with correct runnable programs.

Declaring Multiple Variables of Same Type

Syntax:
Example:
Here:
  • All variables are of type int
  • They are declared in one line
  • Values are assigned separately

Declaring and Assigning in One Line

You can also declare and assign values together.
Each variable gets its own value.

Assigning Same Value to Multiple Variables

Java allows assigning the same value to multiple variables in one statement.
Output:
Java assigns values from right to left.

Using Different Data Types

You cannot declare different data types in one line using a single data type keyword.
Incorrect:
Correct way:
Each data type must be declared separately.

Declaring Multiple String Variables

Works the same way as primitive types.

Best Practice

Although Java allows declaring multiple variables in one line, it is often better to declare them separately for better readability in large projects.
Example of readable style:
Clean code is more important than short code in real world development.

Declaring multiple variables is useful when variables are logically related and share the same data type. Understanding this helps write more structured and organized Java programs.