Constants (static final)
Part of the Object Oriented Programming section of Coddy's Java journey — lesson 18 of 87.
Combining static and final creates a constant - a value that belongs to the class and can never change. This is the standard way to define constants in Java.
public class GameSettings {
public static final int MAX_PLAYERS = 4;
public static final double GRAVITY = 9.81;
public static final String GAME_TITLE = "Space Adventure";
}By convention, constant names use UPPER_SNAKE_CASE to distinguish them from regular variables. Since they're both static and final, you access them through the class name and their values are guaranteed to never change:
System.out.println(GameSettings.MAX_PLAYERS); // 4
// GameSettings.MAX_PLAYERS = 8; // Error! Cannot modifyConstants are typically declared public because they're meant to be shared across your application. Think of values like Math.PI - it's a public static final constant that any code can use.
Why use constants instead of hardcoded values? If you write 4 throughout your code and later need to change it to 6, you'd have to find and update every occurrence. With a constant like MAX_PLAYERS, you change it in one place.
Constants also make code more readable - MAX_PLAYERS is clearer than a mysterious 4.
Challenge
EasyLet's build a MathConstants utility that stores important mathematical values as constants, along with a CircleCalculator that uses those constants to perform calculations.
You'll create two files to organize your code:
MathConstants.java: Create a class that holds mathematical constants usingpublic static finalfields:PIwith value3.14159E(Euler's number) with value2.71828GOLDEN_RATIOwith value1.61803
Main.java: Use your constants to perform circle calculations. You'll receive a radius as input and print three lines:- The area of the circle:
Area: [value] - The circumference of the circle:
Circumference: [value] - The diameter scaled by the golden ratio:
Golden Diameter: [value]
- The area of the circle:
For the calculations:
- Area = PI * radius * radius
- Circumference = 2 * PI * radius
- Golden Diameter = 2 * radius * GOLDEN_RATIO
You will receive one input: the radius (double).
Format all output values to 2 decimal places using String.format("%.2f", value). Access your constants through the class name, like MathConstants.PI.
Cheat sheet
Combining static and final creates a constant - a value that belongs to the class and can never change:
public class GameSettings {
public static final int MAX_PLAYERS = 4;
public static final double GRAVITY = 9.81;
public static final String GAME_TITLE = "Space Adventure";
}By convention, constant names use UPPER_SNAKE_CASE. Access constants through the class name:
System.out.println(GameSettings.MAX_PLAYERS); // 4
// GameSettings.MAX_PLAYERS = 8; // Error! Cannot modifyConstants are typically declared public to be shared across your application. They make code more maintainable and readable by replacing hardcoded values with meaningful names.
Try it yourself
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double radius = scanner.nextDouble();
// TODO: Calculate the area using MathConstants.PI
// Formula: PI * radius * radius
// TODO: Calculate the circumference using MathConstants.PI
// Formula: 2 * PI * radius
// TODO: Calculate the golden diameter using MathConstants.GOLDEN_RATIO
// Formula: 2 * radius * GOLDEN_RATIO
// TODO: Print the results formatted to 2 decimal places
// Use String.format("%.2f", value) for formatting
// Output format:
// Area: [value]
// Circumference: [value]
// Golden Diameter: [value]
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsFields (Attributes)Constructor MethodConstructor OverloadingRecap - Simple Calculator4Inheritance
Basic Inheritance (extends)The super KeywordMethod Overriding (@Override)Constructor ChainingThe Object ClassSingle & Multilevel InheritWhy No Multi Class InheritRecap - Employee Hierarchy7Special Methods & Object Class
toString() Methodequals() and hashCode()clone() MethodcompareTo() and ComparableComparator InterfaceRecap - Custom Sorting2Access Modifiers & Encapsulate
Access Levels OverviewGetter and Setter MethodsInformation HidingThe final KeywordRecap - Bank Account Manager5Polymorphism
Method Overloading BasicsMethod Overriding (Run-Time)Upcasting and DowncastingThe instanceof OperatorAbstract Classes and MethodsRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceAggregation vs CompositionInner Nested & Anonymous ClassEnums and Enum MethodsRecords (Java 16+)Sealed Classes (Java 17+)3Class Props & Static Member
Instance vs Static VariablesStatic MethodsStatic BlocksConstants (static final)Recap - Counter & Utility6Interfaces & Abstract Classes
Introduction to InterfacesImplementing InterfacesMulti Interface ImplemenDefault & Static in InterfaceAbstract Classes vs InterfacesFunctional InterfacesRecap - Payment System