Sharing constant strings in Java across many classes?

java, string

Solution

public static final String CONSTANT_STRING="CONSTANT_STRING";

constants should be:

- public - so that it can be accessed from anywhere

- static - no need to create an instance

- final - since its constants shouldnt be allowed to change

- As per Java naming convention should be capitalized so that easy to read and stands out in Java documentation.

There are instances where interfaces are used just to keep constants, but this is considered a bad practice because interfaces are supposed to define the behavior of a type.

A better approach is to keep it in the class where it makes more sense.

for e.g.

`JFrame` has `EXIT_ON_CLOSE` contant, any class which subclasses `JFrame` will have access to it and it also makes sense to keep in `JFrame` and not in `JComponent` as not all components will have an option to be closed.

Problem

I'd like to have Java constant strings at one place and use them across whole project (many classes). What is the recommended way of achieveing this?

Original source

Related problems