Variables

Constants in Java

A constant is a variable which cannot have its value changed after declaration. It uses the 'final' keyword.


Syntax
modifier final dataType variableName = value; //global constant

modifier static final dataType variableName = value; //constant within a class

Notes

It is convention to capitalize the variable name of a constant.

Declaring a field as 'final' ensures that it is constant and cannot change.

The modifier specifies the scope of the constant.

Constants are very popular with classes. Because the value of a constant doesn't change between created objects, it is usually declared static. The static keyword changes the way the value is accessed: the value of the constant isn't accessed using the object, but with the class name itself.


Example
public final double PI = 3.14; //global constant, outside of a class

//constants within a class
public class Human {
    public static final int NUMBER_OF_EARS = 2;
}

//accessing a class constant
int ears = Human.NUMBER_OF_EARS;

< Variable Declaration   |   Arrays >

© 2019 SyntaxDB. All Rights Reserved.