Â
In Java, a variable is a location in memory where a value can be stored. Variables have a specific data type and a unique name that can be used to access the stored value.
There are three types of variables in Java:
Local variables: Local variables are declared inside a method or a block of code, and can only be accessed within that method or block.Â
They are not initialized by default, and must be given a value before they can be used.
Instance variables: Instance variables are declared inside a class but outside of any method. They are also known as non-static fields.Â
They are associated with an instance of a class and have different values for different objects.Â
They are initialized to their default values (null for reference types and 0 for numeric types) unless they are explicitly assigned a value.
Static variables: Static variables are also known as class variables.Â
They are declared using the static keyword and are associated with the class itself, rather than with any specific instance of the class.Â
They are shared among all objects of the class, and have the same value for all objects.Â
They are initialized to their default values (null for reference types and 0 for numeric types) unless they are explicitly assigned a value.
It is important to note that variables in Java must have a unique name and a specific data type, and the value of a variable can be changed during the execution of the program.
Example:
public class MyClass {
// instance variable
int x = 10;
// static variable
static int y = 20;
Â
public void myMethod() {
// local variable
int z = 30;
// code that uses the variables
}
}
Â
In this example, x is an instance variable, y is a static variable, and z is a local variable.
Post a Comment