Variable is nothing but name of memory location in java.Each variable has the specific data type which defines size and layout of variable’s memory.
There are three kinds of variables in java.
Local variable:
A Variable which is declared inside a method can be termed as “Local Variable”. It is mandatory to initialize local variable otherwise Compiler will complain about it.
Instance variable:
A Variable which is declared at class level can be termed as “Instance variable”. It is not mandatory to initializeInstance variable.
Static variable:
A Variable which is declared as static is known as “Static variable”. Static variables are class level variables.
Let’s understand it with the help of simple program:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
package org.arpit.java2blog;
public class VariableDemo {
int a; // Instance variable
static int b=20; // static variable
public void print()
{
int c=10; // local variable
System.out.println("Method local variable: "+c);
}
public static void main(String args[])
{
VariableDemo demo=new VariableDemo();
System.out.println("Instance variable: "+demo.a); // Printing Instance variable
System.out.println("Static variable: "+b); // Printing static variable
demo.print(); //Printing local variable using print method.
}
}
|
When you run above program, you will get below output:
Instance variable: 0
Static variable: 20
Method local variable: 10
Static variable: 20
Method local variable: 10
That’s all about Variables in java.
0 Comments
If you have any doubts,please let me know