Summary - Constants
- Java course
- Intermediate
- Lesson 41/116
- 5 min
Combine static final and enum constants to write a unit conversion class.
Summary - Constants
In this group you learned static final constants, the uppercase naming convention, constant sets with enum, interface constants and the ready-to-use constants of the Math class. Constants manage immutable values from a single point.
Now you will bring it all together: define constants, create constant sets with enum and calculate with Math constants. Constants are the foundation of robust code design.
Practice Define Circle with the Math constant
Define a class Circle. Add a double radius field. Write a Circle(double r) constructor; assign radius = r;. Add a double area() method returning Math.PI * radius * radius. In main create an instance with new Circle(5.0) and print the result of area().
Starter code
// Define the Circle class
// Add radius field, constructor and area method
// Instantiate and print in mainSample solution
class Circle {
double radius;
Circle(double r) {
radius = r;
}
double area() {
return Math.PI * radius * radius;
}
public static void main(String[] args) {
Circle c = new Circle(5.0);
System.out.println(c.area());
}
}Expected output
78.53981633974483
What comes next?
You learned constants. In the next groups you will define contracts with interfaces, create shared structure with abstract classes and provide flexible behavior with polymorphism. These are the upper layer of object-oriented design.
This group combined static final, the uppercase convention, enum, interface constants and Math constants. These are the foundation of immutable data management. Next you will define contracts with interfaces; you will declare methods that classes must implement.
Practice Define Status enum and Constants class
Define an enum named Status with ACTIVE, PAUSED, STOPPED constants. Define a class Constants with a static final int MAX_RETRY = 3 constant. In a main method write Status s = Status.ACTIVE; and print Constants.MAX_RETRY and s on separate lines.
Starter code
// Define the Status enum
// Add a constant to the Constants class
// Print both in mainSample solution
enum Status { ACTIVE, PAUSED, STOPPED }
class Constants {
static final int MAX_RETRY = 3;
public static void main(String[] args) {
Status s = Status.ACTIVE;
System.out.println(Constants.MAX_RETRY);
System.out.println(s);
}
}Expected output
3 ACTIVE
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What format are constant names written in?
- camelCase
- UPPER_SNAKE_CASE Correct answer
- PascalCase
- lowercase
Explanation: UPPER_SNAKE_CASE — constants are uppercase.
2 Complete the enum definition
enum Color {
RED, GREEN, ____
}
enum Color {
RED, GREEN, BLUE
}
Explanation: Enum constants are uppercase.