A variable is a container which holds the value while the Java program is executed. A variable is assigned with a data type.
Variable is a name of memory location. There are three types of variables in java: local, instance and static.
There are two types of data types in Java: primitive and non-primitive.
A variable declared inside the body of the method is called local variable. You can use this variable only within that method and the other methods in the class aren't even aware that the variable exists.
A local variable cannot be defined with "static" keyword.
A variable declared inside the class but outside the body of the method, is called an instance variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared among instances.
A variable that is declared as static is called a static variable. It cannot be local. You can create a single copy of the static variable and share it among all the instances of the class. Memory allocation for static variables happens only once when the class is loaded in the memory.
public class VariableExample {
// Static variable
private static int staticVar;
// Instance variable
private int instanceVar;
public void someMethod() {
// Local variable
int localVar = 42;
// Using variables
System.out.println("Static Variable: " + staticVar);
System.out.println("Instance Variable: " + instanceVar);
System.out.println("Local Variable: " + localVar);
}
public static void main(String[] args) {
// Accessing static variable
staticVar = 10;
// Creating an instance of the class
VariableExample obj = new VariableExample();
// Accessing instance variable
obj.instanceVar = 20;
// Calling a method that uses local variable
obj.someMethod();
}
}
Комментариев нет:
Отправить комментарий