Java Declare Multiple Variables

In this lesson, we’ll cover how to declare multiple variables in Java and print their values using the println() method. We’ll see how to declare several variables of the same type in one line and how to assign a single value to multiple variables.



Declaring Multiple Variables

If you need to declare several variables of the same type, you can do it in one go by using a comma to separate each variable.

Example:

// Instead of writing:
int a = 1;
int b = 2;
int c = 3;
System.out.println(a + b + c);

// You can simply write:
int a = 1, b = 2, c = 3;
System.out.println(a + b + c);

In this example, we declare and initialize the variables a, b, and c all in one line. The println() method then prints the sum of a, b, and c.




Assigning One Value to Multiple Variables

You can also give the same value to multiple variables in one line. This can make your code look neater.

Example:

int x, y, z;
x = y = z = 100;
System.out.println(x + y + z);

In this example, we assign the value 100 to the variables x, y, and z in one line. The println() method then prints the sum of x, y, and z, which is 300.




Summary

  • Declaring Multiple Variables: Use a comma to declare multiple variables of the same type in one line.
  • Assigning One Value to Multiple Variables: Assign the same value to several variables in one line.
Scroll to Top