In Java, a variable is a container that stores data. Variables allow you to hold different types of data, such as numbers, text, or more complex objects, which can be used and manipulated in a program.
Syntax: To declare a variable in Java:
dataType variableName = value;
Explanation:
dataType: Specifies the type of data the variable will hold (e.g., int, double, String).
variableName: The name of the variable (must follow Java naming rules).
value: The data assigned to the variable (optional during declaration).
Example:
int age = 40; // Declares an integer variable named 'age' with a value of 40.
Rules for Naming Variables
1. Must begin with a letter, _, or $.
2. Cannot use Java keywords (e.g., int, class, etc.).
3. Case-sensitive (MyVar and myvar are different).
4. Should follow camelCase for readability (e.g., studentAge).
Types of Variables
Java variables can be categorized into three main types:
Local Variables
- Declared inside a method, constructor, or block.
- Only accessible within the scope where they are defined.
- No default value; must be initialized before use.
Example:
public void displayAge() {
int age = 40; // Local variable
System.out.println("Age: " + age);
}
Instance Variables
1. Declared inside a class but outside any method, constructor, or block.
2. Each object of the class has its own copy.
3. Default values.
int -> 0double -> 0.0
boolean -> false
String (or any object) -> null
Example:
public class Person {
String name; // Instance variable
int age; // Instance variable
public void displayDetails() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
Static Variables (Class Variables)
Declared with the static keyword.
Shared among all instances of the class.
Memory is allocated once when the class is loaded.
Example:
public class Counter {
static int count = 0; // Static variable
public Counter() {
count++;
}
public static void displayCount() {
System.out.println("Count: " + count);
}
}