Variables
Key Points
- Every variable must be associated with a data type, which can be either a primitive type or a reference type.
- The variable name must be a valid identifier.
- A variable declaration is a complete statement, so it must always end with a semicolon (
;).
Scope
Class Variables (Static)
Syntax:
static DataType variableName; // Initialization is optional
Default Values:
If not explicitly initialized, primitive types default to 0 or 0.0 (and \u0000 for char). Boolean defaults to false. All non-primitive reference types default to null.
Class variables can be acessed directly by other methods within the class.
Instance Variables
Syntax:
DataType variableName; // Initialization is optional
Default Values: The default values are identical to those of class variables.
Note:
To access instance variibles from other methods, you must instantiate the class containing the variable using the new keyword.
Example:
public class Example {
float balance;
public static void main(String[] args) {
Example instance = new Example();
System.out.println(instance.balance);
}
}
The output will be 0.0 since float is a numeric floating-point type.
Local Variables
- Local variables must be declared and initialized with a value.
- They are only accessible within the block or method where they are defined. Attempting to use them outside their scope will result in a compilation error.
Naming Conventions
- General: Choose names that clearly describe the purpose (meaningful names).
- Classes: Use PascalCase (every word starts with a capital letter).
public class UserAccount {} - Variables and Methods: Use camelCase (start with a lowercase letter, then capitalize subsequent words).
double totalAmount; void calculateInterest() {}
Constants
Constants represent immutable data. Once a constant is assigned a value, it cannot be modified during the program's execution. They are essentially special variables with fixed values.
Syntax:
final DataType CONSTANT_NAME = value;
By convention, constant names are written in uppercase letters using underscores to separate words.
Example:
final double MAX_SPEED = 120.50;