Overview
Types of java Constant
Define a Variable as Constant
Example 1
final int distance = 30;
Example 2
final int distance;
distance = 30;
- There are several values in the real world which will never change.
- Sometimes we may need to define some values as constants in our program.
- Nobody should be able to change these values and it should be constant every time.
- One example for a constant is the mathematical constant “pi” which has the value 3.14 every time.
- Constants in java are fixed values those are not changed during the Execution of program
Types of java Constant
- Primitive Data Types
- byte / short / int / long / float / double / boolean / char
- You can define any of these type variables as constants by just adding the keyword “final” when we declare the variable.
- Eg1: final int distance = 30;
- Eg2: final float pi = 3.14f;
Define a Variable as Constant
- To define a variable as constant, we just need to add the keyword “final” in front of the variable declaration.
Example 1
final int distance = 30;
- The above statement declares the int variable “distance” as a constant with a value 30.
- We cannot change the value of distance at any point of time in the program.
- Later if we try to do that by using statements like “distance=40;”, Java will throw errors at compile time itself.
- It is not mandatory that you need to assign values of constants during initialization itself.
Example 2
final int distance;
distance = 30;
- Here we are first defining the int variable distance as a constant.
- Later we are assigning the value 30 to our constant.
- Once this value is assigned, we cannot change this value in the program and if we try to do that by using statements like “distance=40;”, Java will throw errors at compile time itself.