๐ Variables in Java
In Java, variables are used to store data that can be used later in the program. Each variable has a data type and is associated with a name that can be used to reference the value it holds.
๐ง Types of Variables in Java
Instance Variables
- Declared inside a class but outside any method.
- Associated with an object instance.
Local Variables
- Declared inside a method, constructor, or block.
- Exist only within the scope of the method/block.
Static Variables (Class Variables)
- Declared with the
static
keyword. - Shared among all instances of the class.
- Declared with the
Final Variables
- Declared with the
final
keyword. - Cannot be changed once assigned a value.
- Declared with the
๐งช Example: Different Types of Variables
public class VariablesExample {
int instanceVar = 10; // instance variable
public void exampleMethod() {
int localVar = 20; // local variable
System.out.println("Local Variable: " + localVar);
System.out.println("Instance Variable: " + instanceVar);
}
public static void main(String[] args) {
VariablesExample obj = new VariablesExample();
obj.exampleMethod();
}
}
๐จ Important Notes
- Default Values: Variables in Java are assigned default values if not explicitly initialized. For example,
int
defaults to0
, andboolean
defaults tofalse
. - Final Variables: Once assigned,
final
variables cannot be modified.