Junior — Middle
Kas saaksite selgitada, mida tähendab 'final' märksõna kasutamine muutujatele Java keeles?
sobes.tech AI
Vastus AI-lt
In Java, the keyword final when declaring a variable means that after initialization, the value of that variable cannot be changed.
This means:
- For primitive types (
int,boolean, etc.), the value is fixed and cannot be reassigned. - For reference types (
objects), the reference cannot be changed to point to another object, but the object itself can be mutable (if its methods allow it).
Example:
final int x = 10;
x = 20; // Compilation error
final List<String> list = new ArrayList<>();
list.add("item"); // Allowed, the object is modified
list = new ArrayList<>(); // Error, cannot reassign the reference
Using final helps make the code more predictable and safer.