Variables in Java
In Java, variables are containers that hold data that can be manipulated during program
execution. Here's a brief overview:
### Types of Variables in Java
1. **Local Variables**:
- Declared inside a method, constructor, or block.
- Only accessible within the scope where they are defined.
- Must be initialized before use.
2. **Instance Variables** (Non-static fields):
- Declared inside a class but outside any method, constructor, or block.
- Each instance of the class (object) has its own copy.
- Default values are provided if not initialized (e.g., `0` for integers, `null` for objects).
3. **Class Variables** (Static fields):
- Declared with the `static` keyword inside a class but outside any method, constructor, or
block.
- Shared among all instances of the class.
- Default values are provided if not initialized.
### Variable Declaration Syntax
```java
type variableName = value;
```
- `type` specifies the data type of the variable (e.g., `int`, `float`, `String`).
- `variableName` is the name given to the variable.
- `value` is the initial value assigned to the variable (optional during declaration).
### Examples
```java
public class Example {
// Instance variable
int instanceVar = 10;
// Static variable
static int staticVar = 20;
public void method() {
// Local variable
int localVar = 30;
}
}
```
### Variable Scope
- **Local variables**: Limited to the method/block where they are defined.
- **Instance variables**: Accessible by all methods of the class.
- **Static variables**: Accessible by all methods of the class and can be accessed using the
class name.
### Final Variables
- Declared using the `final` keyword.
- Once assigned, their value cannot be changed.
```java
final int constantValue = 100;
```
### Variable Naming Conventions
- Should start with a letter, `$`, or `_`.
- Cannot start with a number.
- Should be meaningful and follow camelCase convention (e.g., `myVariable`).
Understanding these basics about variables in Java is crucial for managing data and writing
effective programs.