Constants
Swipe to show menu
In real applications, not every value should be allowed to change while the program is running. Some values need to stay fixed no matter what happens. These are called constants.
You can think of constants as "locked variables" — once you set them, Java won't allow them to be changed again.
In a coffee shop system, constants are useful for things like:
- tax rates;
- delivery fees;
- maximum number of orders.
If these values change by accident, the program logic can easily break without you noticing.
Creating Constants with final
In Java, we create constants using the final keyword. Once a value is assigned, it becomes permanent:
Main.java
123456789101112131415package com.example; public class Main { public static void main(String[] args) { final double TAX_RATE = 0.20; final int MAX_ORDERS = 10; int currentOrders = 7; System.out.println("Tax rate: " + TAX_RATE); System.out.println("Max orders: " + MAX_ORDERS); System.out.println("Current orders: " + currentOrders); } }
The example declares two constants — TAX_RATE and MAX_ORDERS — using final, which locks their values permanently. currentOrders is a regular variable so it can still change. All three values are printed using println with string concatenation.
To make constants easy to recognize, Java developers follow a specific naming style:
- all letters are UPPERCASE;
- words are separated by underscores.
Examples: TAX_RATE, DELIVERY_FEE, MAX_ORDERS
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat