Constants
Part of the Fundamentals section of Coddy's Java journey — lesson 10 of 73.
A constant is a special type of variable that cannot be changed once it is initialized.
To declare a constant use the keyword final followed by the variable type:
final int MAX_VALUE = 100;In the above example, a constant named MAX_VALUE is initialized with the value 100.
If we try to change a constant value:
final int MAX_VALUE = 100;
MAX_VALUE = 200; // This will cause an errorIt will result in an error because constant values cannot be changed.
Challenge
BeginnerCreate a constant named PI and initialize it with the value 3.14159.
Cheat sheet
A constant is a variable that cannot be changed once initialized. Use the final keyword to declare constants:
final int MAX_VALUE = 100;Constants cannot be reassigned after initialization - attempting to do so will cause an error.
Try it yourself
public class Main {
public static void main(String[] args) {
// Type your code below
// Don't change the line below
System.out.println("PI = " + PI);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 43Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else