Java ยท Chapter 7 of 42
Java Variables
A variable is a named storage location for a value. In Java, every variable must be declared with a specific type, and Java is statically typed, meaning that type cannot change.
Variable names must start with a letter, $ or _, and cannot be a reserved keyword. Java conventions favor descriptive camelCase names.
Syntax
type name = value;
final type NAME = value;Declaring and initializing
A declaration like `int age;` reserves memory for that type. You can also initialize it in the same statement: `int age = 25;`.
Final variables
The `final` keyword makes a variable a constant โ once assigned, it cannot be reassigned.
Example 1 (java)
public class Main {
public static void main(String[] args) {
int age = 25;
final double PI = 3.14;
System.out.println(age + " " + PI);
}
}Output
25 3.14age is a regular variable, PI is a constant declared with final.
Key points
- Every variable has a fixed declared type.
- final makes a variable a constant.
- Names are case-sensitive.
- Java is statically typed.
๐ก Note: Attempting to reassign a final variable causes a compile-time error.
