Header javaperspective.com
JavaPerspective.com  >   Beginner Tutorials  >   3. Java Basics  >   3.4. Constants and enum types

3.4. Constants and enum types
Last updated: 27 January 2013.


3.4.1. Constants

A constant is like a variable whose value cannot be changed. In other words, a constant is a named value. It is good programming style to declare constants in the block they belong to before any other declarations. Thus, if a constant is a class field, it must be declared before variables and methods. Likewise, if a constant is declared within a method, it must be declared before the local variables of the method.

According to the Java code conventions, constants must be written in capital letters with underscores as separators. For example, the following statement declares a maximum weight initialized to 150:

final int MAXIMUM_WEIGHT = 150;

The keyword final is to declare that MAXIMUM_WEIGHT is a constant.


3.4.2. Enum types

An enum type is a fixed set of related constants. For example, if you want to declare a fixed set of 3 colors, you would do it like this:

enum Color { RED, GREEN, BLUE };

By convention, enum types start with a capital letter and the fields contained in an enum type should be written in uppercase letters. The order in which the fields of an enum type are declared is important. In fact, each field has an ordinal. In the example shown above, the ordinal of the field RED is 0, that of the field GREEN is 1 and that of the field BLUE is 2.

This was just an introduction to enum types. You will see how to use them in the tutorial 3.10.


You are here :  JavaPerspective.com  >   Beginner Tutorials  >   3. Java Basics  >   3.4. Constants and enum types
Next tutorial :  JavaPerspective.com  >   Beginner Tutorials  >   3. Java Basics  >   3.5. Operators and expressions

Copyright © 2013. JavaPerspective.com. All rights reserved.  ( Terms | Contact | About ) 
Java is a trademark of Oracle Corporation
Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7