In Java, a symbolic constant is a named constant value defined once and used throughout a program. Symbolic constants are declared using the final keyword.
- Which indicates that the value cannot be changed once it is initialized.
- The naming convention for symbolic constants is to use all capital letters with underscores separating words.
Syntax of Symbolic Constants
final data_type CONSTANT_NAME = value;
- final: The final keyword indicates that the value of the constant cannot be changed once it is initialized.
- data_type: The data type of the constant such as int, double, boolean, or String.
- CONSTANT_NAME: The name of the constant which should be written in all capital letters with underscores separating words.
- value: The initial value of the constant must be of the same data type as the constant.
Initializing a symbolic constant:
final double PI = 3.14159;
Example:
Java
// Java Program to print an Array import java.io.*; public class Example { public static final int MAX_SIZE = 10 ; public static void main(String[] args) { int [] array = new int [MAX_SIZE]; for ( int i = 0 ; i < MAX_SIZE; i++) { array[i] = i * 2 ; } System.out.print( "Array: " ); for ( int i = 0 ; i < MAX_SIZE; i++) { System.out.print(array[i] + " " ); } System.out.println(); } } |
Array: 0 2 4 6 8 10 12 14 16 18