DEV Community

SATHISH BALAJI
SATHISH BALAJI

Posted on

Variables

Variables are the containers for storing the data values or you can also call it a memory location name for the data. Every variable has a:

  • Data Type – The kind of data that it can hold. For example, int, string, float, char, etc.
  • Variable Name – To identify the variable uniquely within the scope.
  • Value – The data assigned to the variable.

Types of Java Variables
There are three types of variables in Java. They are:

  • Local Variables
  • Instance Variables
  • Static Variables

1. Local Variables
A variable defined within a block or method or constructor is called a local variable.
i) The Local variable is created at the time of declaration and destroyed after exiting from the block or when the call returns from the function.
ii) The scope of these variables exists only within the block in which the variables are declared, i.e., we can access these variables only within that block.
iii) Initialization of the local variable is mandatory before using it in the defined scope.

2. Instance Variables (Non-Static)
Instance variables are non-static variables and are declared in a class outside of any method, constructor, or block.

i) As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed.
ii) Unlike local variables, we may use access specifiers for instance variables. If we do not specify any access specifier, then the default access specifier will be used.
iii) Initialization of an instance variable is not mandatory. Its default value is dependent on the data type of variable. For String it is null, for float it is 0.0f, for int it is 0, for Wrapper classes like Integer it is null, etc.
iv) Instance variables can be accessed only by creating objects.

3. Static Variables
Static variables are also known as class variables.

i) These variables are declared similarly to instance variables. The difference is that static variables are declared using the static keyword within a class outside of any method, constructor, or block.
ii) Unlike instance variables, we can only have one copy of a static variable per class, irrespective of how many objects we create.
iii) Static variables are created at the start of program execution and destroyed automatically when execution ends.
iv) Static variables cannot be declared locally inside an instance method.

Top comments (0)