Variable Declaration in Java
Java requires explicit variable declaration before use. The syntax follows:
<data_type> <variable_name> [= initial_value];
Multiple variables can share a type declaration:
int count, index, total; // Three uninitialized integers
double value = 3.14; // Initialized floating-point
boolean isValid = true; // Boolean initialization
String greeting = "Hello World"; // String declaration
char initial = 'A'; // Character assignment
Variable Categories
Java supports three variable scopes:
- Class variables (static fields)
- Instance variables (non-static fields)
- Local variables (method-scoped)
Local Variables
- Declared within methods, constructors, or blocks
- Created upon scope entry and destroyed upon exit
- No access modifiers allowed
- Require explicit initialization before use
Valid Local Variable Example
public class Calculation {
public void compute() {
int result = 0; // Initialized local variable
result = 5 * 10;
System.out.println("Result: " + result);
}
public static void main(String[] args) {
Calculation calc = new Calculation();
calc.compute(); // Output: Result: 50
}
}
Uninitialized Variable Error
public class ErrorExample {
public void process() {
int uninitialized; // Never initialized
uninitialized += 10; // Compilation error
}
}
Error: variable uninitialized might not have been initialized
Instance Variables
- Declared in classes outside methods
- Initialized when objects are created
- Default values: 0 (numeric), false (boolean), null (objects)
- Accessible throughout class methods
Instance Variable Implementation
public class Account {
public String holderName; // Public instance variable
private double balance; // Private instance variable
public Account(String name) {
holderName = name; // Constructor initialization
}
public void deposit(double amount) {
balance = amount; // Method modifies instance variable
}
public void display() {
System.out.println("Account Holder: " + holderName);
System.out.println("Balance: $" + balance);
}
public static void main(String[] args) {
Account acct = new Account("Alice");
acct.deposit(1500.75);
acct.display();
}
}
Account Holder: Alice
Balance: $1500.75
Class Variables (Static Fields)
- Declared with
staticmodifier - Single copy shared across all instances
- Constants use
public static finalnaming convention - Accessed via
ClassName.variableName
Static Variable Implementation
public class Organization {
private static int employeeCount; // Private static variable
public static final String BRANCH = "HQ"; // Public constant
public static void main(String[] args) {
employeeCount = 125;
System.out.println(BRANCH + " staff count: " + employeeCount);
}
}
HQ staff count: 125