Java Constants
Creating unchangeable values in your Java programs
🔒 What are Java Constants?
Java constants are variables whose values cannot be changed once assigned. They are created using the 'final' keyword and help make your code more reliable and maintainable.
public class ConstantExample {
// Class constants (static final)
public static final double PI = 3.14159;
public static final int MAX_STUDENTS = 30;
public static void main(String[] args) {
// Local constant
final String SCHOOL_NAME = "ABC High School";
System.out.println("School: " + SCHOOL_NAME);
System.out.println("PI value: " + PI);
System.out.println("Max students: " + MAX_STUDENTS);
// PI = 3.14; // This would cause an error!
}
}
Output:
School: ABC High School
PI value: 3.14159
Max students: 30
Types of Constants
Local Constants
Constants inside methods
final int MAX_SCORE = 100;
final String GRADE_A = "Excellent";
Class Constants
Constants shared by all instances
public static final double TAX_RATE = 0.08;
public static final String COMPANY = "TechCorp";
Numeric Constants
Mathematical and numeric values
final double PI = 3.14159;
final int DAYS_IN_WEEK = 7;
String Constants
Text values that don't change
final String APP_NAME = "MyApp";
final String VERSION = "1.0.0";
🔹 Creating Constants
Use the 'final' keyword to create constants that cannot be changed:
public class CreateConstants {
// Class-level constants (accessible to all methods)
public static final String APP_NAME = "Student Management System";
public static final double VERSION = 2.1;
public static final int MAX_USERS = 1000;
public static void main(String[] args) {
// Local constants (only accessible in this method)
final int PASSING_GRADE = 60;
final String SEMESTER = "Fall 2024";
final boolean DEBUG_MODE = true;
// Using constants
System.out.println("Application: " + APP_NAME);
System.out.println("Version: " + VERSION);
System.out.println("Max Users: " + MAX_USERS);
System.out.println("Semester: " + SEMESTER);
System.out.println("Passing Grade: " + PASSING_GRADE);
System.out.println("Debug Mode: " + DEBUG_MODE);
// Calculate something using constants
int studentScore = 75;
if (studentScore >= PASSING_GRADE) {
System.out.println("Student passed with score: " + studentScore);
} else {
System.out.println("Student failed with score: " + studentScore);
}
}
}
Output:
Application: Student Management System Version: 2.1 Max Users: 1000 Semester: Fall 2024 Passing Grade: 60 Debug Mode: true Student passed with score: 75
🔹 Why Use Constants?
Constants provide several benefits in your programs:
✅ Benefits of Constants:
- Prevent Accidental Changes: Values cannot be modified
- Code Readability: Meaningful names instead of magic numbers
- Easy Maintenance: Change value in one place
- Prevent Errors: Compiler catches attempts to modify
public class ConstantBenefits {
// Instead of using "magic numbers" throughout code
public static final double SALES_TAX = 0.0825; // 8.25%
public static final int DISCOUNT_THRESHOLD = 100;
public static final double BULK_DISCOUNT = 0.10; // 10%
public static void main(String[] args) {
double itemPrice = 150.0;
int quantity = 3;
double subtotal = itemPrice * quantity;
System.out.println("Subtotal: $" + subtotal);
// Apply bulk discount if applicable
if (subtotal >= DISCOUNT_THRESHOLD) {
double discount = subtotal * BULK_DISCOUNT;
subtotal = subtotal - discount;
System.out.println("Bulk discount applied: -$" + discount);
System.out.println("After discount: $" + subtotal);
}
// Calculate tax
double tax = subtotal * SALES_TAX;
double total = subtotal + tax;
System.out.println("Tax (" + (SALES_TAX * 100) + "%): $" + tax);
System.out.println("Final total: $" + total);
}
}
Output:
Subtotal: $450.0 Bulk discount applied: -$45.0 After discount: $405.0 Tax (8.25%): $33.4125 Final total: $438.4125
🔹 Constant Naming Convention
Follow these naming rules for constants:
public class ConstantNaming {
// ✅ Good constant names (UPPER_CASE with underscores)
public static final int MAX_ATTEMPTS = 3;
public static final String DEFAULT_COLOR = "blue";
public static final double CONVERSION_RATE = 2.54;
public static final boolean ENABLE_LOGGING = true;
// ❌ Poor constant names (avoid these styles)
// public static final int maxAttempts = 3; // Should be UPPER_CASE
// public static final String defaultcolor = "blue"; // Missing underscore
// public static final double rate = 2.54; // Not descriptive enough
public static void main(String[] args) {
// Using well-named constants makes code self-documenting
for (int attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
System.out.println("Attempt " + attempt + " of " + MAX_ATTEMPTS);
if (attempt == 2) {
System.out.println("Success on attempt " + attempt + "!");
break;
}
}
System.out.println("Default color: " + DEFAULT_COLOR);
System.out.println("Inches to CM rate: " + CONVERSION_RATE);
System.out.println("Logging enabled: " + ENABLE_LOGGING);
// Convert inches to centimeters using constant
double inches = 5.0;
double centimeters = inches * CONVERSION_RATE;
System.out.println(inches + " inches = " + centimeters + " cm");
}
}
Output:
Attempt 1 of 3 Attempt 2 of 3 Success on attempt 2! Default color: blue Inches to CM rate: 2.54 Logging enabled: true 5.0 inches = 12.7 cm
🔹 Constants vs Variables
Understanding the difference between constants and variables:
public class ConstantsVsVariables {
// Constant - value never changes
public static final String COMPANY_NAME = "TechSolutions Inc.";
public static void main(String[] args) {
// Variable - value can change
int employeeCount = 50;
String currentProject = "Website Redesign";
// Constant - value cannot change
final double HOURLY_RATE = 25.50;
System.out.println("Company: " + COMPANY_NAME);
System.out.println("Employees: " + employeeCount);
System.out.println("Current project: " + currentProject);
System.out.println("Hourly rate: $" + HOURLY_RATE);
// We can change variables
employeeCount = 55; // ✅ This works
currentProject = "Mobile App Development"; // ✅ This works
System.out.println("\nAfter updates:");
System.out.println("Employees: " + employeeCount);
System.out.println("Current project: " + currentProject);
// We CANNOT change constants
// HOURLY_RATE = 30.0; // ❌ This would cause a compilation error!
// COMPANY_NAME = "New Company"; // ❌ This would also cause an error!
// Calculate weekly pay using constant
int hoursWorked = 40;
double weeklyPay = hoursWorked * HOURLY_RATE;
System.out.println("Weekly pay for " + hoursWorked + " hours: $" + weeklyPay);
}
}
Output:
Company: TechSolutions Inc. Employees: 50 Current project: Website Redesign Hourly rate: $25.5 After updates: Employees: 55 Current project: Mobile App Development Weekly pay for 40 hours: $1020.0