Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Variable

- It is name of memory location.


- It is user defined name given by user.
- Variable can store any type of value.
- One variable can store one information at a time and it can be change.


10
int a = 10




Memory

Types of variable
a) Local
b) Instance/Global
c) Static

a) Local variable :- A variable which declare inside method/block/constructor
called as local variable
Scope of local variable remains only within the method/block/constructor.
Local variable is also called temporary variable.
Syntax:
void add(int a){
int b;
Statements ;
}

b) Instance / Global variable :- A variable which declare inside the class but outside
of all method/block/constructor is called instance variable
scope of global variable remains thought the class.
global variable is also called permanent variable.
Syntax:
Class A{
int a;
Public static void main(){
Statements;
}}

c) Static/ Class variable :- A variable which declare with the help of static keyword
is called as static variable.
1. static variable call from same class -->variableName
2. static variable call from diff class--> className.variableName
Note: we can access static global variable in both static & non-static method



Program :
public class VariableTypes {

static int a = 10; //Instance/ Global variable
static int b = 20; //static variable

public static void main(String[] args) {

int c = 30; //Local variable
final double interest_rate = 7.9; // variable
System.out.println("Global Variable = " + a);
System.out.println("Static Variable = " + b);
System.out.println("Local Variable = " + c);
System.out.println("Local Variable = " + interest_rate);

a = 100;
b = 200;
c = 300;
// d = 400;
}
}


Program :
public class VariableType1 {

static int a =10; //Global/Instance

public static void show()
{
int b=20;
System.out.println("B = " + b);
//21
}

public static void main(String[] args) {
System.out.println("A = " + a);
show();
}
}


Static : The static keyword in Java is used for memory management mainly. We can
create static methods, variables and blocks.
- Static members of class belongs to class itself instead of the Class Object.
- Constructor can’t be static.

- If you declare any variable as static, it is known as a static variable.
- The static variable can be used to refer to the common property of all objects.
- The static variable gets memory only once in the class area at the time of class
loading.

Program
public class VariableTypes5 {

static int a =10; //Static a = 10 11 12 13


int b = 20; //Global/Instance

public void show()


{
a++; //a=11
b++; //b=21
System.out.println(a + " " + b); //11 21 12 21
}

public static void main(String[] args) {


VariableTypes5 a = new VariableTypes5(); //memory1
//a=10->11 b=20->21
a.show(); //b=21
VariableTypes5 b = new VariableTypes5(); //memory2
b.show(); //b=21
//a=11->12 b=20->21
}

You might also like