Java Declare Multiple Variables

Java — Declare Multiple Variables

In Java, you can declare multiple variables of the same data type in a single line. This helps keep your code clean and organized, especially when working with several related variables.


📌 Example: Declaring Multiple Integer Variables

int a = 10, b = 20, c = 30;
System.out.println(a);
System.out.println(b);
System.out.println(c);

✔ All variables (a, b, c) are declared and assigned values in one line.


📌 Example: Declaring Without Assigning Values

int x, y, z;
x = 5;
y = 10;
z = 15;

System.out.println(x + y + z); // Output: 30

You can declare first, then assign values later.


📌 Declare Multiple Variables of Different Types (NOT Allowed in One Line)

❌ You cannot do this:

int a = 10, String name = "John"; // ❌ Error

Different data types must be declared separately:

✔ Correct:

int age = 25;
String name = "John";

📌 Combine Multiple Variable Output

int num1 = 5, num2 = 10, num3 = 15;
System.out.println("Total = " + (num1 + num2 + num3));

📌 Best Practice Tip

If making many variables of same category, group them:

double salary, bonus, tax;

✔ Summary

Style Allowed? Example
Declare multiple same-type variables ✔ Yes int a, b, c;
Declare and assign multiple same-type variables ✔ Yes int a=1, b=2, c=3;
Declare multiple variables with different types in one line ❌ No int a=1, String b="Hello";

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *