Sharing constant strings in Java across many classes?

public static final String CONSTANT_STRING="CONSTANT_STRING";

constants should be:

  1. public – so that it can be accessed from anywhere
  2. static – no need to create an instance
  3. final – since its constants shouldnt be allowed to change
  4. 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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)