Constants in Java

We use Constants in Java to assign a constant value to an object that cannot be changed. Additionally, we use constants to make the code easier to understand.

What are constants in Java?

In Java, a constant is a variable that cannot change value. It becomes beneficial when you want to make sure that a variable does not change the value of mistakes.

 

A constant in Java:

  • Is a variable that cannot change the value 
  • Useful when you want to be sure that a variable does not change the value
  • The best practice is to name a constant with only uppercase letters

It is often a good idea to declare different values as constants. Since this means that we know for sure that the values we want to be constant do not change. Furthermore, we can also use the constants to simplify our code and make it easier to understand, as we will see below.

On the previous page, we illustrated Variables in Java as a box, with a name, where we can then save different values. Similarly, we can imagine constants in Java, though we cannot now open the box and exchange the values. You can think of it as now that we have put a lid on the box and then put a padlock there so that it is not possible to open and exchange that value.

Note, of course, you can use the value inside the box, but not replace it with another.

Declare constants in Java – Syntax

The declaration for constants have similarities to the declaration for variables. That we saw on the page before, but with the difference that constants are declared with the reserved word final. Custom for constants is to name them with capital letters only.

final data type NAME = value;

Constants are declared with the reserved word final. Praxis for constants is to name them in capital letters only.

Example of constant in Java

In the example below,

  • We will calculate how much money there is left each month after the bills are paid
  • Assume that the rent, internet and electricity costs are constant every month
  • Print the result in the console
// Creates three constants, one int for the rent and one for the internet, as well as a double for the home insurance
final int RENT = 4500;      
final int INTERNET = 100; 
final double HOMEINSURANCE = 79,50;   

// Enter your salary 
int salary = 20000;
// Calculates how much money is left after bills are paid
double moneyAfterBills = salary - (RENT + INTERNET + HOMEINSURANCE);

// Printing the result 
System.out.println("Money left after the bills are paid: " + moneyAfterBills);

Which in this case gives the print

Money left after the bills are paid: 15320.5

Because we use constants, it becomes much easier to see what happens in the calculation moneyAfterBills. Now this was a vert simple example, but in the case of large applications, constants can facilitate much for your own sake but also for another programmer to understand what the program does in different calculations.

Previous Page    |    Next Page