Search code examples
javaconstants

What's the proper way of declaring project constants in Java?


This may seems a silly question for Java developers, however, I'm new to Java, and my background is from low level c. I used to include an header file with all the constants that were relevant for my projects. (usually #define's). I'm working on a big Java project now, and there a few constants I need to make global (they fit in more than one class, and used in various parts of the project )

It makes it hard for me to decide where to put it, should I declare the same constant few times, one in each class ?

A lot of framework, uses XML files to declare constants & definitions for the framework (Hibernate, Log4J, etc.) Is it wise to use this kind of technique in my project ? if so, how can it be done easily ?


Solution

  • As with many things, there are many ways to do it. One thing you should not do is declare them multiple times - that's just plain silly. :P

    Everything has to be in a class in Java, so either:

    1. Pick a "main" class (say I have a project called "FTPServerApp" - I could put them there)
    2. Create a "Util" class that contains all of them

    When you figure out where to put them, declare them all this way:

    public static final [type] [NAME_IN_ALL_CAPS] = [value];
    

    This will

    • make them available to all your project code, anywhere (public)
    • only one copy of the value exists across all instances of the class (static)
    • they cannot be changed (final).

    The ALL_CAPS_FOR_CONSTANT_NAMES, separated by underscores, is the convention in Java.

    So, if this was declared in a class called FTPServerAPP, and you had a constant called SERVICE_PORT it might be:

    public class FTPServerApp {
      public static final int SERVICE_PORT = 21;
    
      ...
    }
    

    ...and you would access it, from any class, like this...

      FTPServerApp.SERVICE_PORT