From the course: Java 8 Essential Training

Unlock the full course today

Join today to access over 22,400 courses taught by industry experts or purchase this course individually.

Using static variables as constants

Using static variables as constants - Java Tutorial

From the course: Java 8 Essential Training

Start my 1-month free trial

Using static variables as constants

- Many programming languages support the concept of a constant. A variable, whose value can't be changed. There is a const keyword in Java, but it's not currently implemented. Instead Java developers create constants using the final keyword. Final, when applied to a variable, means that its value can only be set once. I'm going to demonstrate this in the project Constants. Right now, in my Main class I'm setting the names of my olives with simple strings. That works fine, but it's problematic because it's easy to misspell it, and to be inconsistent. So, I'm going to add constants to the Olive class. One for each type of olive I want to support. And then I'll refer to those constants in my Main class. I'll place my constant declarations at the top of the Olive class. Each of the constants will be public and static, so I'll be able to refer to the constant from the class declaration. And it'll be final. And it'll be a string. There's a strong naming convention for constants. They should…

Contents