In this blogpost we will discuss the different types of variables in Java. But before that lets see the naming conventions which are followed/allowed in Java programming language.
- Variables naming cannot contain white spaces, for example: int num ber = 100; (invalid)
- Variable name can begin with special characters such as $ and _.
- As per the java coding standards the variable name should begin with a lower case letter.For lengthy variables names that has more than one words do it like this: int smallNumber; int bigNumber; (start the second word with capital letter). This technique is referred as camelcase.
- Variable names are case sensitive in Java.
There are three types of variables in Java.
- Local variable
- Static (or class) variable
- Instance variable
Static (or class) Variable
Static variables are also known as class variable because they are associated with the class and common for all the instances of class. For example, If I create three objects of a class and access this static variable, it would be common for all, the changes made to the variable using one of the object would reflect when you access it through other objects.
Do note that only static variables can be accessed like this. This doesn’t apply for instance and local variables.
Instance variable
Each instance(objects) of class has its own copy of instance variable. Unlike static variable, instance variables have their own separate copy of instance variable. We have changed the instance variable value using object obj2 in the following program and when we displayed the variable using all three objects, only the obj2 value got changed, others remain unchanged. This shows that they have their own copy of instance variable.
Local Variable
These variables are declared inside method of the class. Their scope is limited to the method which means that You can’t change their values and access them outside of the method.