Constants in Java

Jul 10, 2024

Lecture on Constants in Java

Outline

  • Definition of Constants
  • Ensuring a Constant Value
  • Benefits of Using Constants

What is a Constant?

  • A variable whose value cannot be changed
  • Defined using the final keyword
  • Naming conventions:
    • All uppercase letters
    • Snake case (e.g., CONSTANT_NAME)
  • Syntax error if value is changed

Creating a Constant

  • Syntax: final data_type CONSTANT_NAME = value;
  • Example:
    final String COMPANY_NAME = "Nazar Academy";
    System.out.println(COMPANY_NAME);
    

Benefits of Using Constants

  1. Prevent Accidental Changes:
    • Value can't be altered, preventing mistakes
  2. Reuse of Values:
    • Avoids typing the same value multiple times
    • Easy to update value in one place
  3. Improved Readability:
    • Descriptive names make the code easier to understand

Demonstration in IDE

  • Example project creation and constant implementation
  • Steps to create a new project in IDE:
    • File > New Project > Next > Project from template > Next
    • Name project, e.g., Nazar Academy
    • Option to change package name
    • Finish project setup
  • Implementing and printing a constant:
    final String COMPANY_NAME = "Nazar Academy";
    System.out.println(COMPANY_NAME);
    
  • Attempting to reassign a constant displays an error:
    COMPANY_NAME = "Another Name"; // Error: Cannot assign a value to final variable
    
  • Declaration and assignment split:
    final String COMPANY_NAME;
    COMPANY_NAME = "Nazar Academy"; // First-time assignment allowed
    
  • Duplicating and fixing typo example:
    • Typing mistake Nazar instead of Nazar
    • Using constant to avoid multiple fixes
    • Updating constant updates all instances
    final String COMPANY_NAME = "Nazar Academy"; // Corrects mistake everywhere
    

Summary

  • Constants ensure unchangeable values
  • Prevent errors and duplicates
  • Enhance code readability

End of Lecture