Introduction to Constants in Java
Constants in Java are fixed values that do not even change during the program execution. We use the “final” keyword to store the constant value throughout the program’s execution. It prevents accidental changes to the useful values in the Java program.
We can use constants to store values that don’t change, such as mathematical constants like Pi or configuration settings. Declining a value as a constant makes our code easier to read, keeps our data consistent, and stops accidental changes. This all helps make our Java programs solid and easy to manage.
In Java, below are the different types of constants.
- Integer constants
- Real constants
- Character constants
- String constants
Table of Contents
Syntax
final data_type CONSTANT_NAME = value;
Where
- “final” indicates that the variable is a constant, and its value cannot change.
- “data_type” specifies the data type of the constant.
- “CONSTANT_NAME” is the constant’s name, which follows Java naming conventions (e.g., using uppercase letters with underscores to separate words).
- The “value” is the initial value assigned to the constant, which you must provide during declaration and cannot alter afterward.
Example
Code
public class ConstantsExample {
// Declaring a constant for the value of pi
static final double PI = 3.14159;
public static void main(String[] args) {
// Using the constant PI in calculations
double radius = 5.0;
double area = PI * radius * radius;
// Printing the calculated area
System.out.println("Area of the circle: " + area);
}
}
Output:
Explanation
- In the above example, “PI” is a constant with the value of “3.14159”. We use the “final” keyword to calculate the circle’s area.
- The “System.out.println” statement will display the value to the console.
- The static modifier makes a constant accessible without creating an instance of its class. It’s useful for memory management.
- The “final” modifier makes a variable’s value unable to be altered, making it immutable.
Key Takeaways
- Constants are fixed values that do not change throughout program execution.
- Java constants are immutable.
- It is declared using the “final” and “static” keywords.
- Constants are categorized as numeric and non-numeric.
- Further categorize as integer, real, character, and string constants.
Why do we use Constants?
Using constants in Java offers several advantages in your development process. We can use constants for the following reasons.
- Improves code readability- constants have descriptive naming conventions, explaining their purpose in the program, making it easier for any developer to understand the code logic without help. Enhances code readability and simplifies maintenance.
- Optimizing memory usage- constants improve the code performance by minimizing memory usage. The constants are stored in the memory only once when defined and declared and can be accessed multiple times throughout the program. They optimize memory resources and usage, regardless of frequency of use.
- Easy code tracking– as the value of the constants remains consistent throughout the program, it makes it easier to track the code while debugging and refactoring. It means that if you need to change the constant value, it can be done from a single place, reducing the risk of errors in making frequent code changes.
- Data encapsulation and simplification- as a constant encapsulates data within a single variable, it simplifies data management. Instead of scattering data across multiple parts of the codebase, constants provide a centralized location for accessing and managing related data, improving code organization and readability.
- Reduce error- as constants are centralized and usually defined at the program’s start, making changes becomes easier, reducing the risk of making errors by changing the constant values across the codebase.
- Preventing magic numbers- magic numbers are numeric literals used directly in code without explanation or context, for example (Pi). Assigning values to named constants makes the code more self-explanatory and easier to modify if the value needs to change in the future.
Types of constants
In Java, below are the different types of constants.
- Numeric constants
- Non-numeric constants
These are further categorized:
1. Numeric constants
Numeric constants represent fixed numerical values. They can be integer constants, real constants, or a combination of both. It consists of a leading sign and a decimal point.
It is simple to declare a numeric constant in Java.
- It should have at least a single digit.
- It should not include any special symbol, space, or comma.
- The value can be positive or negative. If there is no sign by default, it is considered a positive numeric constant.
Below are two types of numeric constants: integer and real constants.
A. Integer Constants
Integer constants range from (0-9) and are whole numbers without any fractional or decimal part. They can be positive, negative, or zero. Integer constants are further categorized as follows:
- Decimal constants- A decimal constant represents a whole number in the base-10 system. The digits can vary between 0 and 9, stipulating that the first digit cannot be “0” unless the number is zero. You can use them to store values such as counts or measurements. For example, 496, 3317, and 1883 are all examples of decimal constants.
- Octal constants- An octal constant represents a number in the octal system, base-8. The digits vary between 0 to 7; the first digit is always “0”. You can use them to represent bit flags, permissions, or other settings—for example, 092, 055, and 02784.
- Hexadecimal constants- Hexadecimal constants are numeric constants that represent the numbers in the hexadecimal (base-16) system. The digits vary between 0 to 9 and then A to F (or a to f), prefixed with “0x” or “0X”. You can use them to store memory addresses, bitwise operations, and color representations. For example, 0x1B, 0xBD, and 0xFFAC.
B. Real Constants
Real constants, or real or floating-point constants, are numbers with fractional or decimal parts. They can be positive, negative, or zero. To represent the floating-point constant as float, we use either “f” or “F” in the end. For example- 11F, 3.7f, -0.32f.
You can represent real constants in two forms-
- Fractional form- including at least one digit, a decimal point, and optionally, a positive or negative sign, excluding commas, spaces, or other symbols. For example- -8.2, 0.44, 2.56.
- Exponential form- Use this when the real constant is too small or too large. For example, to represent 0.00000149, we use this form as 1.49e-6. The part before “E or e” is called mantissa, while the rest is called the exponent and must have one digit. Both mantissa and exponent can be positive or negative, but by default, they are positive.
2. Non-numeric Constants:
As the name suggests, these constants do not contain numbers. Character constants, backslash character constants, and string constants categorize them.
A. Character Constants
Character constants represent individual characters enclosed within single quotes. They can include letters, digits, symbols, or escape sequences. For example- ‘A,’ ‘7’, ‘*,’ ‘\n.’
B. String Constants
String constants represent sequences of characters enclosed within double quotes. They can include any combination of letters, digits, symbols, or escape sequences. For example- “Hello,” “Java,” “123”, and “Special characters: ~!@#$%^&*()_+”.
C. Backslash character constants used in output methods are escape sequences with Unicode values. For example, ‘\n,’ ‘\t,’ and others. Being two characters, it only represents a single character. These are non-printable characters starting with the “\” backslash character.
D.
Escape Sequence | Description |
\n | Newline |
\t | Tab |
\b | Backspace |
\r | Carriage Return |
\f | Form Feed |
\’ | Single Quote |
\” | Double Quote |
\\ | Backslash |
\a | Alert |
\e | Escape |
\uXXXX | Unicode |
Let’s take an example to understand the types of Constants:
public class ConstantsExample {
// Integer Constants
public static final int INTEGER_CONSTANT = 100;
// Real Constants
public static final double REAL_CONSTANT = 3.14159;
// Character Constants
public static final char CHARACTER_CONSTANT = 'A';
// String Constants
public static final String STRING_CONSTANT = "Hello, Java!";
// Octal Constants
public static final int OCTAL_CONSTANT = 075; // Represents decimal value 61
// Hexadecimal Constants
public static final int HEX_CONSTANT = 0xAB; // Represents decimal value 171
// Backslash Character Constants
public static final String BACKSLASH_CONSTANT = "\\n"; // Represents newline character
public static void main(String[] args) {
// Printing all constants
System.out.println("Integer Constant: " + INTEGER_CONSTANT);
System.out.println("Real Constant: " + REAL_CONSTANT);
System.out.println("Character Constant: " + CHARACTER_CONSTANT);
System.out.println("String Constant: " + STRING_CONSTANT);
System.out.println("Octal Constant: " + OCTAL_CONSTANT);
System.out.println("Hexadecimal Constant: " + HEX_CONSTANT);
System.out.println("Backslash Character Constant: \"" + BACKSLASH_CONSTANT + "\"");
}
}
Output:
Declaring Constants in Java
Example 1: Implementing Energy equivalent of Mass (E = mc2)
Code:
public class MathConstants {
// Static constant for the speed of light in meters per second
public static final double SPEED_OF_LIGHT = 299792458.0;
// Static constant for the gravitational constant in meters per second squared
public static final double GRAVITATIONAL_CONSTANT = 9.80665;
public static void main(String[] args) {
// Using the constants in calculations
double mass = 10.0; // Mass in kilograms
double energy = mass * Math.pow(SPEED_OF_LIGHT, 2); // E = mc^2
double weight = mass * GRAVITATIONAL_CONSTANT; // Weight = mass * gravity
// Printing the calculated values
System.out.println("Energy equivalent of mass: " + energy + " Joules");
System.out.println("Weight of the object: " + weight + " Newtons");
}
}
Output:
Explanation:
- We define two constants, SPEED_OF_LIGHT and GRAVITATIONAL_CONSTANT, representing the speed of light and the gravitational constant, respectively.
- The constants are then used in calculations to find the energy equivalent of mass (using the famous equation E = mc^2) and the weight of an object.
- The function prints the calculated values to the console.
Example 2: Constant as Public
Declaring a constant as public in Java means allowing access outside the class where it’s declared. The “public” access modifier makes it visible to other classes in the same package or other packages if the class is part of a public API. Other classes can use that constant without creating an instance of the class where the constant is defined.
Code:
class ClassA {
public static final double SUM = 44.4;
}
public class ClassB {
public static void main(String[] args) {
System.out.println("Value of SUM: " + ClassA.SUM);
}
}
Output:
Explanation:
- In The above example, SUM is a public constant variable declared within ClassA.
- As declared public, it’s accessible from anywhere in the program.
- In this scenario, ClassB attempts to access the constant variable from ClassA.
- The code runs successfully because the public access modifier declares the constant, allowing external classes like ClassB to access it.
- This example demonstrates the accessibility of public constants across different classes within the same program.
Example 3: Constant as Private
Declaring a constant as private in Java means you can only access this constant within its class. You cannot access or modify this constant value outside the class, including other classes in the same package or classes that extend the class containing the constant.
Code:
class ClassA {
private static final double SUM = 44.4;
}
public class ClassB {
public static void main(String[] args) {
// Attempting to access private constant SUM from ClassA
// Results in a compilation error
System.out.println("Value of SUM: " + ClassA.SUM);
}
}
Output:
Explanation
- The above example declares a private constant variable named SUM within ClassA.
- ClassB attempts to access ClassA.SUM, resulting in a compilation error.
- You can access private constants only within the class where they’re defined (ClassA in this case).
- When you access ClassA.SUM from ClassB violates the encapsulation principle and results in a compilation error, highlighting the restriction imposed by the private access modifier on constants.
We Can Solve this using this method:
Code:
class ClassA {
private static final double SUM = 44.4;
// Getter method to access the private constant
public static double getSum() {
return SUM;
}
}
public class ClassB {
public static void main(String[] args) {
// Accessing the private constant SUM from ClassA using the getter method
System.out.println("Value of SUM: " + ClassA.getSum());
}
}
Output:
Explanation;
- ClassA provides a public static method getSum() to access the private constant SUM.
- The getSum() method returns the value of the private constant SUM.
- ClassB calls the getSum() method from ClassA to obtain the value of the constant.
- This approach ensures encapsulation of the constant’s value within ClassA.
- Other classes can access the constant indirectly through the getter method, maintaining encapsulation while allowing controlled access to the constant’s value.
Advantages of Using Java Constants
Using constants offers numerous advantages for developers.
- Enhanced Data Security– Constants enhance data security by ensuring their values remain immutable once declared. It prevents accidental changes to critical codebase, maintaining data integrity and security.
- Reduced Likelihood of Coding Errors- Constants reduce the chance of coding errors by eliminating the need for lengthy text or values to be repeatedly used across the codebase. You can define constants in a single place, minimizing the likelihood of typographical errors and inconsistencies in the code.
- Improved Code Readability and Maintenance- Constants improve code readability by allowing you to use descriptive names for constants. It helps other developers understand the code logic and make changes without errors.
- Compile-time type checking- using constants will help detect errors and ensure type safety, preventing runtime issues related to data types.
- Improves performance- Constants can improve code performance by enabling compiler optimizations, such as constant folding and inlining, leading to faster and more efficient code execution.
- Maintains data integrity- as constants are immutable whose values remain consistent throughout the program’s execution, improving data integrity and safety.
Examples of Constants in Java
Creating a Constant Class
A constants Class is a separate class declaring and defining constant values. It contains public static final fields with different constant values. Keeping all these constants in one class allows you to easily manage and access them from any part of your application for better code organization, readability, and maintainability.
Code:
class Constants {
// Constants for colors
public static final String RED = "RED";
public static final String GREEN = "GREEN";
public static final String BLUE = "BLUE";
// Constant for maximum allowed attempts
public static final int MAX_ATTEMPTS = 3;
// Constant for default timeout in milliseconds
public static final long DEFAULT_TIMEOUT_MS = 5000;
// Constant for PI
public static final double PI = 3.14159;
}
public class Main {
public static void main(String[] args) {
// Accessing constants from the Constants class
System.out.println("Red color constant: " + Constants.RED);
System.out.println("Maximum allowed attempts: " + Constants.MAX_ATTEMPTS);
System.out.println("Default timeout in milliseconds: " + Constants.DEFAULT_TIMEOUT_MS);
System.out.println("Value of PI: " + Constants.PI);
}
}
Output:
Explanation
- We have a Constant class that contains several public static final fields representing constant values.
- These constants include colors (RED, GREEN, BLUE), a maximum allowed attempts constant (MAX_ATTEMPTS), a default timeout constant (DEFAULT_TIMEOUT_MS), and the mathematical constant PI.
- In the Example class, we access these constants by referencing the Constants class followed by the dot operator (.) and the constant name.
Constants in Real-world Applications
You can use constants to define configuration parameters such as database connection details, server addresses, API keys, and application timeouts. By centralizing these values as constants, it becomes easier to manage and modify them.
AppConfig.java
public class AppConfig {
// Configuration parameters
public static final String DATABASE_URL = "jdbc:mysql://localhost:3306/mydatabase";
public static final String DATABASE_USERNAME = "EDUCBA";
public static final String DATABASE_PASSWORD = "admin";
public static final int CONNECTION_TIMEOUT = 5000; // 5 seconds
}
DatabaseConnection.java
public class DatabaseConnection {
public static void main(String[] args) {
// Accessing configuration parameters
String dbUrl = AppConfig.DATABASE_URL;
String username = AppConfig.DATABASE_USERNAME;
String password = AppConfig.DATABASE_PASSWORD;
int timeout = AppConfig.CONNECTION_TIMEOUT;
// Simulating database connection
System.out.println("Connecting to database...");
System.out.println("Database URL: " + dbUrl);
System.out.println("Username: " + username);
System.out.println("Password: " + password);
System.out.println("Connection timeout: " + timeout + " milliseconds");
// Code to establish database connection goes here
}
}
Output:
Explanation:
- The AppConfig class contains constants representing configuration parameters such as database URL, username, password, and connection timeout.
- The DatabaseConnection class demonstrates accessing these configuration parameters and simulates establishing a database connection.
- When running the DatabaseConnection class, it outputs the configuration parameters to the console. Developers use constants to define and access configuration settings.
When to Use Java Constants:
In the following scenarios, you can use Java constants.
- Use Java constants when a value remains constant throughout program execution.
- Utilize constants for defining and managing configuration parameters like database connections and timeouts.
- Replace obscure numeric values, known as “magic numbers,” with meaningful constants to enhance code readability and maintainability.
- Employ constants such as PI and Euler’s number for accuracy and clarity in mathematical and scientific calculations.
- Standardize error handling using constants for error codes, messages, and exceptions, facilitating easier troubleshooting.
- Represent business rules, thresholds, and constraints with constants to ensure consistency and clarity in application logic.
- Define constants for styling attributes like colors and font sizes to maintain a consistent user interface appearance.
Enumerations (Enums) as Constants
Enumerations, known as enums, are a special data type that defines a set of named constants. Enums represent a fixed set of predefined values to make the code more readable, maintainable, and type-safe. You can use enumerations to use primitive data types or constants to represent a finite set of related values.
Developers can use enums to explicitly list all possible values an enum variable can take, ensuring they use only valid ones. Enums also enable type-checking at compile-time, preventing errors due to invalid or misspelled constant values.
Example
// Define an enum for days of the week
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
// Main class to demonstrate usage of the Day enum
public class EnumExample {
public static void main(String[] args) {
// Accessing enum constants
Day today = Day.WEDNESDAY;
// Switch statement with enum
switch (today) {
case MONDAY:
System.out.println("Today is Monday");
break;
case TUESDAY:
System.out.println("Today is Tuesday");
break;
case WEDNESDAY:
System.out.println("Today is Wednesday");
break;
// More cases for other days...
default:
System.out.println("Today is not a weekday");
break;
}
}
}
Output:
In this example-
- We define an enum called Day, representing the days of the week. Each constant within the enum (SUNDAY, MONDAY, etc.) represents a specific day.
- In the EnumExample class, we demonstrate using the enum constants. We assign Day.WEDNESDAY to the variable today.
- We then use a switch statement to perform different actions based on the value of the today variable. This switch statement is more readable and type-safe than integer or string constants.
Advance Technique
1. Constant Folding and Inlining
Constant folding and inlining are two advanced techniques that help compilers for code optimization. Let’s understand about both of them in detail.
Folding
Constant folding evaluates the continuous expressions at compile time rather than runtime. This optimization replaces expressions involving constants with their computed values, which saves unnecessary computations during program execution.
Example
final int x = 5;
final int y = 10;
final int result = x + y; // The expression is folded to `final int result = 15;
Inlining
Inlining embeds the code of a small function directly into the calling code rather than invoking the function separately. This optimization reduces function call overhead and improves performance, especially for small and frequently used functions.
Example
// Original method definition
public int add(int a, int b) {
return a + b;
}
// After inlining
public int add(int a, int b) {
return a + b;
}
// The call site
int result = add(5, 10); // The call site is replaced with `int result = 5 + 10;
Let’s use both techniques as an example.
Code
public class ConstantFoldingInliningExample {
// Constant variables
public static final int X = 5;
public static final int Y = 10;
// Method to demonstrate inlining
public static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
// Constant folding example
final int result = X + Y; // The expression is folded to `final int result = 15;`
System.out.println("Constant Folding Example: " + result);
// Inlining example
int inlinedResult = add(5, 10); // The call site is replaced with `int result = 5 + 10;`
System.out.println("Inlining Example: " + inlinedResult);
}
}
Output:
Explanation
Constant Folding Example:
- We create a class named ConstantFoldingInliningExample.
- Inside the class, we declare two constant variables, X and Y.
- In the main method:
- We perform constant folding by adding the constants X and Y, resulting in a computed value of 15.
- The program assigns this computed value to the variable result.
- We then print the result of the constant folding example.
Inlining Example:
- We explain inlining by calling the add method with arguments 5 and 10.
- The compiler replaces the method call with the actual addition operation.
- It provides the same value of 15.
- The program assigns the result to the variable inlinedResult.
- Finally, we print the result of the inlining example.
2. Constants in Multithreaded Environments
In multithreaded environments, constants ensure thread safety and prevent race conditions. You must use constants properly to avoid data corruption and synchronization issues when working with shared resources across multiple threads.
Contants.java
public class Constants {
public static final int MAX_THREADS = 10;
}
WorkThread.java
public class WorkerThread implements Runnable {
public void run() {
// Accessing the constant
int maxThreads = Constants.MAX_THREADS;
// Perform thread-safe operations
System.out.println("Thread " + Thread.currentThread().getId() + " is executing.");
}
}
Main.java
public class Main {
public static void main(String[] args) {
// Creating and starting multiple worker threads
for (int i = 0; i < Constants.MAX_THREADS; i++) {
Thread thread = new Thread(new WorkerThread());
thread.start();
}
}
}
Output:
3. Internationalization and Constants
Internationalization (i18n) is designing and developing software applications that support multiple languages and cultural conventions. Constants in internationalization provide a centralized way to manage text, messages, and other locale-specific resources. Let’s see the below example.
InternationalizationExample.java
import java.util.Locale;
import java.util.ResourceBundle;
public class InternationalizationExample {
// Constants for message keys
public static final String GREETING_KEY = "greeting";
public static final String FAREWELL_KEY = "farewell";
public static void main(String[] args) {
// Set the desired locale
Locale locale = new Locale("fr", "FR"); // French locale
// Load the appropriate resource bundle based on the locale
ResourceBundle messages = ResourceBundle.getBundle("Messages", locale);
// Retrieve and display the messages using constants
String greeting = messages.getString(GREETING_KEY);
String farewell = messages.getString(FAREWELL_KEY);
System.out.println(greeting); // Output: Bonjour!
System.out.println(farewell); // Output: Au revoir!
}
}
Messages.properties
greeting=Hello!
farewell=Goodbye!
Messages_fr_FR.properties
greeting=Bonjour!
farewell=Au revoir!
Output:
Explanation
- The InternationalizationExample class showcases constant usage for managing localized messages.
- Locale Setting:
- The demonstration chooses the French locale (fr_FR).
- Resource Bundle Loading:
- The appropriate resource bundle (Messages_fr_FR.properties) is loaded based on the locale.
- Retrieving Messages:
- The program uses constants (GREETING_KEY and FAREWELL_KEY) to fetch localized messages.
- Output Display:
- The program prints French greetings (“Bonjour!”) and farewell (“Au revoir!”) messages.
Best Practices
Below are some best practices for working with constants in Java.
- Use clear and descriptive names for constants.
- Declare constants as final to enforce immutability.
- Write constants in uppercase to differentiate them from variables.
- Consolidate related constants within dedicated classes or interfaces.
- Organize related constants together for better code organization.
- Avoid using raw numeric values directly in code; use constants with meaningful names.
- Provide explicit comments or documentation for constants.
- Consider using enums for sets of related constants.
- Declare constants near their usage to improve code locality.
- Prioritize the use of constants over hardcoded values for easier maintenance.
Common Pitfalls and misconception
- Overusing: Using constants excessively can clutter code and reduce flexibility. It’s essential to judiciously use them only for values that genuinely remain constant throughout the application.
- Tight Coupling: Placing all constants in a single class or interface tightly couples unrelated parts of the codebase. This mistake makes understanding and maintaining the code harder, especially as it grows.
- Lack of Documentation: Failing to document constants properly can confuse developers who may need help understanding their purpose or usage. Developers should provide explicit comments or documentation for each constant to explain its significance.
- Magic Numbers: While constants replace magic numbers for clarity, blindly replacing every numeric value with a constant can lead to overly verbose code. Developers should evaluate each usage case to ensure it adds clarity without unnecessary complexity.
- Performance Concerns: Constant folding and inlining can improve performance, but premature optimization can make code harder to understand and maintain. Constants should be optimized for performance only when necessary, avoiding premature optimization.
Conclusion
Constants in Java are immutable values that do not change throughout the program. It makes the program easy-to-understand and readable. Constant variables are cached by JVM and the app, thus improving the app’s performance significantly. Different types of constants help you make your code more effective.
Frequently Asked Questions (FAQs)
Q1. Can constants be declared with different access modifiers?
Answer: Developers can declare constants with public, private, or protected access modifiers. However, Developers commonly declare them as public and static if they intend for constants to be accessed globally.
Q2. Is it possible for constants in Java to have different data types?
Answer: Yes, constants can have different data types in Java, including primitive types (e.g., int, double) and object types (e.g., String, Date). Developers should choose each constant’s data type based on the nature of the value it represents.
Q3. Can constants be initialized at runtime in Java?
Answer: In Java, constants typically initialize at compile time, and their values cannot change during runtime. This initialization ensures that they remain constant throughout the execution of the program.
Recommended Articles
We hope that this EDUCBA information on “Constants in Java” was beneficial to you. You can view EDUCBA’s recommended articles for more information,