Variables
What is Variable?
Variable is the name of memory location which can store the data.
int a = 10;
int = data type
a = variable
10 = literal (data)
Value of variable can be vary – lets understand with example
int a = 10;
a = a + 20;
logic -- a = 10 +20;
a = 30;
// 10 values came from previous variable which is declared as int a =10;
Type of Variable
- Local Variable
- Instance Variable
- Static Variable
Note :- Global Variable is not present in Java – it is present in C and C++ -- In Java we use instance variable
- Local Variables :-
- Declaration :- Inside Method, Constructors or Block
- Scope :- Inside Method, Constructors or Block not outside of the this.
- When Variables get allocated :- When Method, Constructors or Blocs get executed, variable allocates the memory and when Method, Constructors or Block get exist – Variable get deleted from the memory
- Stored Memory :- Local variable get allocated/stored in Stack Memory.
- Default Value :- Doesn’t have any default value – we have to provide the value before use else system throws error
- Access Specifiers :- cannot use with local variables else system throws error.
- Instance Variable :-
- Declaration :- Inside the class but outside of the Method, Constructors or Block
- Scope :- Inside all Method, Constructors or Block within a class (but not inside the static method directly – to use within a static method we have to create an object of the class then of the class then by object reference we have to call the variable).
- When Variables get allocated :- When object is created variable get allocated memory and when object gets deleted variable releases memory.
- Stored Memory :- Instance variable get allocated/stored in Heap Memory.
- Default Value :- They have default values
Int = 0 , boolean = false , object = null.
- Access Specifiers :- can be use with instance variables.
- How to use :- 1. We can call directly if is a simple method. 2. In case of static method – we have to create the object of the class and then we will call the variable with object reference.
- Static Variable :-
- Declaration :- Inside the class with static keyword but outside of the Method, Constructors or Block.
- Scope :- Inside all Method, Constructors or Block within a class including static method, static Constructors or static Block.
- When Variables get allocated :- When we run the program and .class file is loaded static variable get allocated and when .class file get unloaded variable get delated.
- Stored Memory :- static variable get allocated/stored in Non heap Memory or Static Memory.
- Default Value :- They have default values
Int = 0, boolean = false, object = null.
- Access Specifiers :- can be use with static variables.
- How to use :- 1. Directly 2. Bys using class name (class name . Variable name == ABC.b ----- class = ABC and variable =1) 3. By using object reference name Like instance variable.