Java Variables

By | September 29, 2021
Java Variables

Variables are used to hold some value within the Java program. You can define the variable with the data type and can assign the value of that particular data type. Variable can be considered to be the name given to the memory location. Variables can be of three types- local, instance and static.

Two types of data types- primitive and non-primitive that can be used for the variables within Java.

What are Variables?

Variables are those whose value can be changed. It is the name that specifies the memory allocated that can contain a value.

For example:

int var=10;

Types of variables

Variables can be classified on the basis of their scope. There are three types of variables.

1. Local variable

The variable whose scope exists within the method is called the local variable. Other methods within the class cannot access this variable. You cannot declare a local variable with the static keyword.

2. Instance variable

The variable which is declared within a class but outside the method body is called instance variable. You cannot declare this variable as static. The value of this variable depends on the instance and cannot be shared among different instances. It means you cannot use this variable within another class.

Vamware

3. Static Variable

Once a variable is declared as static, you cannot declare it as local. You can use the static variable among all instances of the class. The memory will be allocated for the static variable only once when the class gets loaded in memory.

Example

class demo{ 
int var1=50;//instance variable 
static int var2=100;//static variable 
void method(){ 
int var3=90;//local variable 
} }//end of class

People are also reading:

Leave a Reply

Your email address will not be published. Required fields are marked *