What is a variable
It is a container to store data values.
Each Variable has:
- Datatype
- Variable Name:
- Values
Why Do We Need Variables?
To store user inputs and to perform calculations etc
Syntax of a Variable in Java
dataType variableName = value;
Types of Variable Scope in Java:
- Local Variable
- Instance Or Object or Global Variable
- Static Variable
What is a Local Variable
It is declared inside a class and inside a method, and it must be initialized. It can be accessed only within that method. It will be destroyed once the block finishes execution.
Syntax:
void display() {
int x = 10; // local variable
System.out.println(x);
}
- It cannot be used outside the display() method.
- It must be called from the main method using object creation and accessed by calling
object reference name. method name
What is a Global Variable:
- It is declared inside the class and outside the method.
We just declare the variables inside the class and the values will be initialized during object creation.
It can be accessed using
Objet reference name . Variable name
Syntax
class Student {
String name; // instance variable
}
What is a Static Variable:
- Declared using the static keyword
- Belongs to the class, not to objects
- Shared among all objects of the class. Instead of each object having its own copy, there's only ONE copy that all objects share.
Syntax:
class College {
static dataType variableName;
Example: static String companyName = "ABC Pvt Ltd";
}
You can access it in these ways below:
- Inside the class, it can be accessed by just using the variableName.
- Outside the class, it can be accessed by ClassName.VaribleName
Top comments (0)