JAVA Variables


JAVA Variable stores, retrieve and manipulate information. A variable reserve some space in computer memory in order to store the information. A variable can be defined and then assigned it a value in some later stage or it can be assigned some value while declaring the variable at the same time.  It is called initialization of the variable and value assigned to the variable at that time is called default value.
In order to define the variables in JAVA we need two things one is Data Type and other is name of the variables, Below is the examples of three variables where rollnumber, name and sal are variable and int,char and double are the data types of these variable.

int rollnumber = 3;
char name = 'X';
double sal;

datatype define the type of the data that can be stored or assigned to variable e.g rollnumber can only stores INTERGER values, name can only stores single CHARACTER value and sal can stores a decimal value.

There are few rules for while naming variable in JAVA.
1.       A variable name should be meaningful
2.       JAVA is case sensitive, so that it differentiate between upper and lower case letters
3.       A variable cannot be started with digit or special symbols like %,#,@ etc and we cannot use them inside the these while naming the vaiables.
4.       A variable name can contains only letters, digits and underscore
5.       Keywords cannot be used in order to name the variables. Keywords are specific constants which have specific meaning and task in the Computer Language and defined by the compiler of the language.
6.       It is good practice to use camel case naming while writing variable names for example


int RollNumber = 3;
char Name = 'X';
double AnnualSal;


Types Of Variables in JAVA:
There are 3 types of variables in JAVA:
1. Local Variable
2. Instance variable
3. Class Variable/Static variable
Local variable:
  • These are also called as stack variable. Because they exist in stack memory
  • It is mandatory to initialize the local variable. Otherwise you will get run time error from compiler
  • These can be defined inside method, constructor or also inside block. The scope or life time of local variable destroyed with end of method completion.
Instance variable:
  • Instance variable are also known as member variable or field
  • These are associated with the object creation. As the object get created instance variable also get created
  • These live on heap memory. In case, if you don’t initialize instance variable with initial value these get default value at run time implicitly.
Class Variable/Static Variable:
  • These are loaded and initialized when class is loaded in JVM
  • There exists only one copy of class variable
  • They live on heap memory. If these variables are not initialized to some default value is assigned to them implicitly.