Learn Java

Learn Declare Multiple Variables In Java

Learn How To Declare Multiple Variables

If you want to declare more than one variable or multiple variables of the same type, you can use a comma-separated list:

For example, instead of writing:

int x = 41;

int y = 71;

int z = 71;

System.out.println(x + y + z);

Learn Declare Multiple Variables In Java

 

 

You can simply write the code:

public class Main {

  public static void main(String[] args) {

    int x = 4, y = 7, z = 50;

    System.out.println(x + y + z);

  }

}

 

Output:

Learn Declare Multiple Variables In Java 2

 

Give One Value to Multiple Variables

You can also assign the same value to multiple variables in one line.

 

Code Example:

public class Main {

  public static void main(String[] args) {

    int x, y, z;

    x = y = z = 100;

    System.out.println(x + y + z);

  }

}

 

Output: 300

Learn Declare Multiple Variables In Java 3