Before a variable can be used in a Java program, it must be declared.
The following code shows how to declare a variable.
int num1; // Declaration of a variable num1
The following code declares an int variable num2 and assigns 50 to it:
int num2; // Declaration of a variable num2 num2 = 50; // Assignment
public class Main { public static void main(String[] args) { int num2; // Declaration of a variable num2 num2 = 50; // Assignment System.out.println(num2);// w ww .j a va2 s.c om } }
The following code declares an int variable num3 and initializes it to a value 100:
int num3 = 100; // Declaration of variable num3 and its initialization
public class Main { public static void main(String[] args) { int num3 = 100; // Declaration of variable num3 and its initialization System.out.println(num3);//from w w w . j a v a 2 s . co m } }
To declare more than one variable of the same type in one declaration, separate each variable name by a comma.
// Declaration of three variables num1, num2 and num3 of type int int num1, num2, num3;
To declare more than one variable in one declaration, and initialize some or all.
Declaration of variables num1, num2 and num3. Initialization of only num1 and num3
int num1 = 10, num2, num3 = 20;
Declaration and initialization of variables num1, num2 and num3
int num1 = 10, num2 = 20, num3 = 30;