Constants in Java

Notes:

Constants in Java Programming Language:

What is a variable & constant?

Variable:
Variable is a named memory location, whose value can change during the execution of a program.

Constant:
Constant is a named memory location, whose value never changes during the execution of a program once it is initialized or assigned.

Creating constants in Java:
- Constants in Java are created using final keyword
- Constants are also called final variables

Note: Final variables must be initialized when they are declared

Syntax for declaring and initializing a constant:
final datatype NAME_OF_CONSTANT = value;
Ex:
final float PI = 3.142f;

Syntax for declaring and initializing multiple constants:
final datatype NAME_OF_CONSTANT1 =value, NAME_OF_CONSTANT2 =value,...;
Ex:
final float PI = 3.142f, E = 2.71828f;

Example Code:

package constantsdemo;

public class ConstantsDemo
{
public static void main(String[] args)
{
/*
int playerScore = 0;
System.out.println("player score = " + playerScore); // 0

playerScore = 10;
System.out.println("player score = " + playerScore); // 10

final float PI = 3.142f;
System.out.println("PI = " + PI);//3.142

// PI = 4.142f; error

*/

final float PI=3.142f, E=2.71828f;
System.out.println("PI = " + PI); // 3.142
System.out.println("E = " + E); // 2.71828
}
}