Definition-

It’s a name of memory block which can hold any value.

memorypic1

Types of variable in java-

1- Instance variable
2- Local variable
 3- Static variable or class variable

1- Instance variable-It’s
-declared in class, not in any local field such as method, constructor etc)
-used on instance/objects.

2- Local variable– It’s
-declared in any local field such as method, constructor etc.
-used within local fields.

3-Static/class variable– It’s
-declared in class with static keyword
-used on class name.

code samples are here

1- Program to create 2 instance variable, ‘String s’ with value “asd” and ‘int i’ with value 10 and print them using object


package var5;

public class ExVar1 {
String s="asd"; //instance variable
int i=10; //instace variable
public static void main(String[] args) {
Var1 v = new Var1();
System.out.println(v.i);
System.out.println(v.s);
}
}

2- Program to create 2 Local variable, ‘int a’ with value 10 inside method show and ‘String n’ with value asdfg inside constructor and use both method and constructor to print them.

package var5; 

public class ExVar2 {
void show(){
int a=10;
System.out.println(a);
}
Var3(){
String n="asdfg";
System.out.println(n);
}
public static void main(String[] args) {
Var3 v1 = new Var3();
v1.show();
}
}

3- Program to create static variable, ‘int a’ with value 20  and print it using class name.

package var5;
public class ExVar3 {
static int a=20;
public static void main(String[] args) {
System.out.println(Var2.a);
}
}
Advertisements