JAVA VARIABLES
Java constants
When a variable’s value must not change after its first assignment, Java uses the keyword final. It prevents reassignment and clearly communicates the developer’s intention.
What does final do?
The keyword final is written before the variable’s type. Once a value is assigned, the same variable cannot receive another value:
final int skaicius = 15;
skaicius = 20; // Error: a final variable cannot be assigned a new value The second statement would cause a compiler error. The program cannot run until the attempt to change the value of skaicius is removed.
final is not a separate data type.The type is still int; final only prevents another assignment.
When should you use final?
final is suitable for values that must stay the same while the program runs. These might be business rules, fixed quantities or values whose accidental modification would cause an error.
final int MINUTES_PER_HOUR = 60;
final int DAYS_PER_WEEK = 7;
final int BIRTH_YEAR = 1980;MINUTES_PER_HOURis always60.DAYS_PER_WEEKin this model is always7.BIRTH_YEARfor a particular person should not be accidentally changed during a calculation.
Constant names
By the usual Java convention, constants are written in uppercase, with underscores separating words: MAX_LOGIN_ATTEMPTS or SECONDS_PER_MINUTE.
This is not a compiler requirement. It is a readability convention that helps readers recognise values that should not change.
You can assign the value later, but only once
final local variable can be declared without an initial value. However, it must receive a value before use, and that assignment can happen only once:
final int maksimalusGreitis;
maksimalusGreitis = 120; // The first assignment is allowed
// maksimalusGreitis = 130; // A second assignment would cause an errorThis is useful when the value becomes known only after a calculation or a method returns, but must remain unchanged afterwards.
A final reference and a mutable object
For objects, final prevents the reference from being changed to another object. This does not necessarily mean that the
final StringBuilder tekstas = new StringBuilder("Java");
tekstas.append("Quest"); // The object’s contents can be changed
// tekstas = new StringBuilder("Kitas"); // The reference cannot be changed The variable tekstas will always refer to the same StringBuilder object, but you can still add to that object’s contents. True object immutability also requires an appropriate class design.
What should you remember?
finalvariable receives a value only once.- Reassignment causes a compiler error.
- Constant names are often written in
UPPER_SNAKE_CASEstyle. finalreference does not always make the object itself immutable.- Use
finalwhen a change would be illogical or unsafe.