"Seleniums.com is where I keep my notes organized."

Constants

Estimated reading: 3 minutes 9 views

In Java, constants are values that cannot be changed once they are assigned. Constants are useful when you want to ensure that certain values in your program remain unchanged throughout its execution. Java provides the final keyword to declare constants.

The final Keyword

The final keyword in Java is used to define variables, methods, and classes that cannot be modified after they are initialized or declared.

When applied to a variable, the final keyword makes that variable a constant, meaning its value cannot be changed once assigned. Similarly, final can be used to prevent methods from being overridden or prevent classes from being subclassed.

1. Declaring Constants with final

To declare a constant, you use the final keyword along with the variable declaration. It’s common practice to use uppercase letters for constant names, with words separated by underscores.

Syntax:

				
					final dataType CONSTANT_NAME = value;

				
			

Example:

				
					final int MAX_AGE = 100;
final double PI = 3.14159;
final String COUNTRY = "USA";

				
			

Once assigned, the values of these constants cannot be modified throughout the program.

2. Benefits of Using Constants

  • Avoid Magic Numbers: Constants make your code more readable and maintainable by replacing hard-coded values with meaningful names.
  • Prevent Errors: By using constants, you prevent accidental modifications of values that should remain fixed.
  • Improved Code Maintenance: Constants allow you to change a value in only one place, making your code easier to maintain.

3. Example of Constants in Java

Here’s an example showing how to use constants in Java:

				
					public class ConstantsExample {
    // Declaring constants
    final int MAX_SPEED = 120;
    final double TAX_RATE = 0.07;
    final String COMPANY_NAME = "TechCorp";

    public void displayInfo() {
        System.out.println("Max Speed: " + MAX_SPEED);
        System.out.println("Tax Rate: " + TAX_RATE);
        System.out.println("Company Name: " + COMPANY_NAME);
    }

    public static void main(String[] args) {
        ConstantsExample example = new ConstantsExample();
        example.displayInfo();
    }
}

				
			

Output:

				
					Max Speed: 120
Tax Rate: 0.07
Company Name: TechCorp

				
			

In this example:

  • MAX_SPEED, TAX_RATE, and COMPANY_NAME are constants.
  • Their values cannot be changed after initialization.

4. Constants in Classes and Methods

  • Constant in Methods: You can also use final for method parameters, ensuring that their values are not changed inside the method.
  • Constant in Classes: When you declare a class as final, it cannot be subclassed.

Example: Final Parameter in a Method

				
					public class FinalMethodExample {
    public void displayFinalValue(final int value) {
        // value = 100; // Error: Cannot assign a value to final variable
        System.out.println("Value: " + value);
    }

    public static void main(String[] args) {
        FinalMethodExample example = new FinalMethodExample();
        example.displayFinalValue(10);
    }
}

				
			

Example: Final Class

				
					final class MyClass {
    // This class cannot be subclassed
}

class SubClass extends MyClass { // Error: Cannot subclass final class
    // Code will not compile
}

				
			

Key Points to Remember

  • The final keyword makes variables, methods, and classes immutable or unmodifiable.
  • Constants in Java are declared using the final keyword, ensuring their values cannot be changed once initialized.
  • Constants are typically named in uppercase letters with underscores separating words (e.g., MAX_SPEED).

Leave a Comment

Share this Doc

Constants

Or copy link

CONTENTS