What is Variable
Variable is a name which is used to store a value of specified type during program execution. The type can be a int, float, String etc, variable also refers as a container that contains assigned value.
A variable has a name, a type, and a value associated with it. For example, int a = 10; here, a is a variable of int type contains integer value 10.
Variable Declaration and Initialization
Creating a variable can be done in either a single or two following steps:
- Variable Declaration
- Variable Initialization
Variable declaration is to specify type of a variable and its name. For example below, we are declaring two variables a and b of type int and float respectively.
Variable Initialization means initializing variable with a specified type value. For example
We can combine both the steps into single statement to declare and initialize variable at the same time.
Variable Naming Conventions
In Java, Creating a variable require some rules and naming conventions. Following are the summerized variable naming conventions.
- Variable names are Case Sensitive. "abc" and "ABC" both are different variable names.
- Variable name should not be a reserve or keyword word.
- Variable name can be started with lowercase, dollar ($) sign or the underscore (_) character only. But it is recommended to always begin variable names with a letter, not "$" or "_".
- Use full meaningful words instead of abbreviations. Doing so will make code easier to read and understand
- If variable name consists of multiple words, capitalize the first letter of each subsequent word. For example, currentTime, topSpeed etc.
Types of Variables
Instance Variables (non-static variables)
Class Variables (static variables)
Local Variables (method automatic variables)
A variable which is declared inside the class (not inside method) without static keyword are called instance variables. This variable belongs to the object of class and has unique value for each individual object. It is called non-static because it does not allow to use static keyword while creating variable.
A variable which is declared using static keyword is known as static variable. This variable belongs to class and has exactly single copy. It is called class variable because it initialize when class is loaded into memory and belongs to class. We can access it using class name only.
A variable which is declared inside a method is known as local variable. Local variable is only visible to the method in which it is declared; it is not accessible from outside of the method.