Variable and types of variables in java Programming language :-
What is variable in Java
Variable is a memory location name of the data.
Variable in Java is a data Container that stores the data values during Java program execution.
Every variable is assigned Java type whitch designates the type & quantity of value it can store.
There are three main types of variable in java:
1. Local Variable.
2. Instance Variable.
3. Static Variable.
To declare a variable, you must specify the data type & give the variable a unique name.
Ex. int roll_no ;
int -> is a data type, roll_no -> is a Variable name.
Variable Initialisation:-
To initialize a variable, you must assign it a valid value.
roll_no = 33;
Hence, Container named"roll_no" holding a value 33.
We can also write Declaration and initialisation in one line.
For example,. int roll_no = 33;
Types of variable :
- Local Variable.
- Instance Variable.
- Static Variable.
- Local Variable :-
A variable declared inside the body of method is called as a local variable. We can use this variable only within that method and the other method is in the class are not even use this variable.
2. Instance Variable:-
An instance variable is declared anywhere inside a class outside any method its visible to all methods of that class it can be accessed from outside that class.
it created when and new instance of the class is created and destroyed when there are no longer reference to that instance
Instance variable are defined using the static keyword. They are defined outside a method declaration.
They are object Pacific and noun as instance variable.
Ex.
class student
{
int marks = 50; //instance Variable
Void method ( )
{
int n = 90; // Local Variable
}
}
3. Static Variable:-
A variable which is declared as static keyword is called as static Variable.
The scope of the static variable is exactly same as the scope of the class.
static variable in a class are initialised before any object of that class can be created.
static variable will be created at the time of class loaded and destroyed at the time of class unloaded.
Static variable are initialised when class is loaded.
Syntax:
Static<Data type> <Variable_name>;
Ex.
Static int age;
Example
class student
{
int marks = 50; //instance Variable
Void method ( )
{
int n = 90; // Local Variable
}
}