How to create constants in Java?

A constant in java cannot be changed, but can an initial value be assigned through another variable ?

For example, if we have in our program a method that hypothetically calculates the import rate of a product through its location and returns a value double, but this value cannot be changed in the course of the program, it must remain the same as the value initially returned in order to be applied elsewhere in various ways possible.

So can I assign the value it returned to a constant? What are the ways to "unchanged" a value that has been calculated from another(s)?

Author: Maniero, 2019-01-05

1 answers

Java doesn't have constants, but it's not what you want. Java has read-Only variables, or as it likes to call that its value is finalized, so it can be put into the variable during object construction, then it can no longer be changed. It is done like this:

public final BigDecimal taxa;

The secret there is final which does not allow the variable to be changed, except within the constructor.

I Used BigDecimal because if it is a value that will be used for monetary calculation probably need accuracy, which double does not give.

If you want a greater control and allows you to change under certain circumstances there is no way. The solution would be the use of a method setter that analyzes whether or not it can change and makes the change or not, or still does not have a method of this and only internally it make a change decision in some case, but never invoked directly by the consumer of the class in order only to change its value. This is a case that can be necessary if you only know the value after the constructed object.

 2
Author: Maniero, 2020-08-21 17:25:22