can be used to store information/data. Once a variable is declared, it can be initialized with some value and later can be changed to some other value. A variable can be used further for performing any calculations, printing it etc., Every variable should have a datatype
etc., and that type should be specified at the time of declaring the variable. Every variable should also have a unique (or non duplicate) name to identify it.
For example, in a student program we can have one variable to store 'the section of the student', one for 'roll number' etc.
tells the data type of the variable and
gives the variable name. Similarly
is the data type and the variable name is
You can assign a value to a variable at the same time that it is declared. This process is known as initialization
char section = 'C';
int roll_number = 76; //assign 76 to roll number
defines the data type of the variable and
gives the variable name, where 76
is the current value of the variable.
As shown above, one variable (
) in your program can store numeric data while another variable (
) can store char data. Java has special keywords to signify what type of data each variable stores. We can declare variables using the keywords/types explained in Data Types In Java
and initialze the value of the variable.
Rules for naming variables:
- No spaces in variable names
- No special symbols in variable names such as !@#%^&*
- Variable names can only contain alphabets, numbers, and the underscore ( _ ) symbol
- Variable names can not start with numbers, but variable name can contain numbers
- Variables are case-sensitive,
numberOfStudents is different from
Lets see a simple program using the variables.
Print variable value
public static void main(String arg)
int numberOfStudents = 34; // LINE A
int highestMarks = 98;
System.out.println("The class has " + numberOfStudents + " students and the highest marks are " + highestMarks + ".");
The class has 34 students and the highest marks are 98.
Here we declared variables
highestMarks. Both of them are of type
int. We have concatenated varialables and strings to print the formatted output.
THINGS TO TRY
- Change the
25 and observe the output.
- Add one more double variable
averageMarks and set it to
53.2. Print the average marks in the format "Average marks are 53.2".
LINE A, change the variable name from
numberofstudents (change O and S from capitals to small letters) but do not change it in the print statement. Observe the compilation error you get. Note that the variable names are case-sensitive.
- Try declaring the variables with names like
number of students and see what compilation errors you get.