CHAPTER 16

image

Constants

A variable in Java can be made into a constant by adding the final keyword before the data type. This modifier means that the variable cannot be reassigned once it has been set, and any attempts to do so will result in a compile-time error.

Local constants

A local constant must always be initialized at the same time as it is declared. The Java naming convention for constants is to use all uppercase letters and to separate the words with underscores.

final double PI = 3.14;

Constant fields

Class and instance variables can also be declared as final.

class MyClass{   final double E = 2.72;  static final double C = 3e8;}  

Get Java Quick Syntax Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.