In Java, a variable is a named container that holds a value. Variables are used to store and manipulate data in a program. There are three types of variables in Java:
- Local Variables: These variables are declared inside a method or block of code and have a limited scope. They can only be accessed within the block of code where they are declared.
Example:
public void myMethod() {
int x = 10; // local variable
System.out.println(x);
}
- Instance Variables: These variables are declared inside a class but outside of any method, and they have class-level scope. They can be accessed and modified by any method in the class.
Example:
public class MyClass {
int x; // instance variable
public void myMethod() {
x = 10;
System.out.println(x);
}
}
- Static Variables: These variables are also declared inside a class but are marked with the “static” keyword. They have class-level scope and can be accessed without creating an instance of the class.
Example:
public class MyClass {
static int x; // static variable
public static void myMethod() {
x = 10;
System.out.println(x);
}
}
Variables in Java can have different data types, such as int, double, boolean, etc. The data type determines the type of data that can be stored in the variable. Variables can also be initialized with an initial value when they are declared, or they can be assigned a value later in the program.