Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Constants | Variables and Data Types
Introduction to Java

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

Main.java

123456789101112131415
package 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

question mark

Why would you use a constant instead of a variable?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 8

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 2. Chapter 8
some-alt