<p>I've seen examples like this: </p>

<pre><code>public class MaxSeconds {
   public static final int MAX_SECONDS = 25;
}
</code></pre>

<p>and supposed that I could have a Constants class to wrap constants in, declaring them static final. I know practically no Java at all and am wondering if this is the best way to create constants.  </p>

[{'answer_id': 66076, 'author': 'jjnguy', 'author_id': 2598, 'author_profile': 'https://Stackoverflow.com/users/2598', 'pm_score': 10, 'selected': True, 'text': '<p>That is perfectly acceptable, probably even the standard.</p>\n\n<pre><code>(public/private) static final TYPE NAME = VALUE;\n</code></pre>\n\n<p>where <code>TYPE</code> is the type, <code>NAME</code> is the name in all caps with underscores for spaces, and <code>VALUE</code> is the constant value;</p>\n\n<p>I highly recommend NOT putting your constants in their own classes or interfaces. </p>\n\n<p>As a side note:  Variables that are declared final and are mutable can still be changed; however, the variable can never point at a different object.</p>\n\n<p>For example:</p>\n\n<pre><code>public static final Point ORIGIN = new Point(0,0);\n\npublic static void main(String[] args){\n\n    ORIGIN.x = 3;\n\n}\n</code></pre>\n\n<p>That is legal and <code>ORIGIN</code> would then be a point at (3, 0).</p>\n'}, {'answer_id': 66096, 'author': 'Joel Martinez', 'author_id': 5416, 'author_profile': 'https://Stackoverflow.com/users/5416', 'pm_score': 0, 'selected': False, 'text': '<p>I wouldn\'t call the class the same (aside from casing) as the constant ... I would have at a minimum one class of "Settings", or "Values", or "Constants", where all the constants would live.  If I have a large number of them, I\'d group them up in logical constant classes (UserSettings, AppSettings, etc.)</p>\n'}, {'answer_id': 66123, 'author': 'Jason Cohen', 'author_id': 4926, 'author_profile': 'https://Stackoverflow.com/users/4926', 'pm_score': 3, 'selected': False, 'text': '<p>That\'s the right way to go.</p>\n\n<p>Generally constants are <em>not</em> kept in separate "Constants" classes because they\'re not discoverable.  If the constant is relevant to the current class, keeping them there helps the next developer.</p>\n'}, {'answer_id': 66142, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>Just avoid using an interface:</p>\n\n<pre><code>public interface MyConstants {\n    String CONSTANT_ONE = "foo";\n}\n\npublic class NeddsConstant implements MyConstants {\n\n}\n</code></pre>\n\n<p>It is tempting, but violates encapsulation and blurs the distinction of class definitions.</p>\n'}, {'answer_id': 66143, 'author': 'Andrew Harmel-Law', 'author_id': 2455, 'author_profile': 'https://Stackoverflow.com/users/2455', 'pm_score': 0, 'selected': False, 'text': "<p>To take it a step further, you can place globally used constants in an interface so they can be used system wide.  E.g.</p>\n\n<pre><code>public interface MyGlobalConstants {\n    public static final int TIMEOUT_IN_SECS = 25;\n}\n</code></pre>\n\n<p>But don't then implement it.  Just refer to them directly in code via the fully qualified classname.</p>\n"}, {'answer_id': 66212, 'author': 'Sébastien D.', 'author_id': 5717, 'author_profile': 'https://Stackoverflow.com/users/5717', 'pm_score': 3, 'selected': False, 'text': '<p>What about an enumeration?</p>\n'}, {'answer_id': 66228, 'author': 'MetroidFan2002', 'author_id': 8026, 'author_profile': 'https://Stackoverflow.com/users/8026', 'pm_score': 8, 'selected': False, 'text': "<p>I would highly advise against having a single constants class.  It may seem a good idea at the time, but when developers refuse to document constants and the class grows to encompass upwards of 500 constants which are all not related to each other at all (being related to entirely different aspects of the application), this generally turns into the constants file being completely unreadable.  Instead:</p>\n\n<ul>\n<li>If you have access to Java 5+, use enums to define your specific constants for an application area.  All parts of the application area should refer to enums, not constant values, for these constants.  You may declare an enum similar to how you declare a class.  Enums are perhaps the most (and, arguably, only) useful feature of Java 5+.</li>\n<li>If you have constants that are only valid to a particular class or one of its subclasses, declare them as either protected or public and place them on the top class in the hierarchy.  This way, the subclasses can access these constant values (and if other classes access them via public, the constants aren't only valid to a particular class...which means that the external classes using this constant may be too tightly coupled to the class containing the constant)</li>\n<li>If you have an interface with behavior defined, but returned values or argument values should be particular, it is perfectly acceptible to define constants on that interface so that other implementors will have access to them.  However, avoid creating an interface just to hold constants: it can become just as bad as a class created just to hold constants.</li>\n</ul>\n"}, {'answer_id': 66307, 'author': 'Marcio Aguiar', 'author_id': 4213, 'author_profile': 'https://Stackoverflow.com/users/4213', 'pm_score': 7, 'selected': False, 'text': "<p>It is a <strong>BAD PRACTICE</strong> to use interfaces just to hold constants (named <em>constant interface pattern</em> by Josh Bloch). Here's what Josh advises:</p>\n\n<blockquote>\n  <p>If the constants are strongly tied to\n  an existing class or interface, you\n  should add them to the class or\n  interface. For example, all of the\n  boxed numerical primitive classes,\n  such as Integer and Double, export\n  MIN_VALUE and MAX_VALUE constants. If\n  the constants are best viewed as\n  members of an enumerated type, you\n  should export them with an <strong>enum</strong>\n  type. Otherwise, you should export the\n  constants with a noninstantiable\n  utility class.</p>\n</blockquote>\n\n<p>Example:</p>\n\n<pre><code>// Constant utility class\npackage com.effectivejava.science;\npublic class PhysicalConstants {\n    private PhysicalConstants() { }  // Prevents instantiation\n\n    public static final double AVOGADROS_NUMBER   = 6.02214199e23;\n    public static final double BOLTZMANN_CONSTANT = 1.3806503e-23;\n    public static final double ELECTRON_MASS      = 9.10938188e-31;\n}\n</code></pre>\n\n<p>About the naming convention:</p>\n\n<blockquote>\n  <p>By convention, such fields have names\n  consisting of capital letters, with\n  words separated by underscores. It is\n  critical that these fields contain\n  either primitive values or references\n  to immutable objects.</p>\n</blockquote>\n"}, {'answer_id': 66339, 'author': 'shelfoo', 'author_id': 3444, 'author_profile': 'https://Stackoverflow.com/users/3444', 'pm_score': 5, 'selected': False, 'text': '<p>In Effective Java (2nd edition), it\'s recommended that you use enums instead of static ints for constants.</p>\n\n<p>There\'s a good writeup on enums in Java here:\n<a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html" rel="noreferrer">http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html</a></p>\n\n<p>Note that at the end of that article the question posed is:</p>\n\n<blockquote>\n  <p>So when should you use enums?</p>\n</blockquote>\n\n<p>With an answer of:</p>\n\n<blockquote>\n  <p>Any time you need a fixed set of constants</p>\n</blockquote>\n'}, {'answer_id': 66343, 'author': 'Rob Dickerson', 'author_id': 7530, 'author_profile': 'https://Stackoverflow.com/users/7530', 'pm_score': 3, 'selected': False, 'text': '<p>I agree that using an interface is not the way to go. Avoiding this pattern even has its own item (#18) in Bloch\'s <a href="http://java.sun.com/docs/books/effective/" rel="nofollow noreferrer">Effective Java</a>.</p>\n\n<p>An argument Bloch makes against the constant interface pattern is that use of constants is an implementation detail, but implementing an interface to use them exposes that implementation detail in your exported API.</p>\n\n<p>The <code>public|private static final TYPE NAME = VALUE;</code> pattern is a good way of declaring a constant. Personally, I think it\'s better to avoid making a separate class to house all of your constants, but I\'ve never seen a reason not to do this, other than personal preference and style.</p>\n\n<p>If your constants can be well-modeled as an enumeration, consider the <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html" rel="nofollow noreferrer">enum</a> structure available in 1.5 or later.</p>\n\n<p>If you\'re using a version earlier than 1.5, you can still pull off typesafe enumerations by using normal Java classes. (See <a href="http://www.javapractices.com/topic/TopicAction.do?Id=1#Legacy" rel="nofollow noreferrer">this site</a> for more on that).</p>\n'}, {'answer_id': 66592, 'author': 'Yann Ramin', 'author_id': 9167, 'author_profile': 'https://Stackoverflow.com/users/9167', 'pm_score': 4, 'selected': False, 'text': '<p>The number one mistake you can make is creating a globally accessible class called with a generic name, like Constants. This simply gets littered with garbage and you lose all ability to figure out what portion of your system uses these constants.</p>\n\n<p>Instead, constants should go into the class which "owns" them. Do you have a constant called TIMEOUT? It should probably go into your Communications() or Connection() class. MAX_BAD_LOGINS_PER_HOUR? Goes into User().  And so on and so forth. </p>\n\n<p>The other possible use is Java .properties files when "constants" can be defined at run-time, but not easily user changeable. You can package these up in your .jars and reference them with the Class resourceLoader.</p>\n'}, {'answer_id': 66768, 'author': 'mmansoor', 'author_id': 9984, 'author_profile': 'https://Stackoverflow.com/users/9984', 'pm_score': 0, 'selected': False, 'text': '<p>For Constants, Enum is a better choice IMHO. Here is an example</p>\n\n<p>public class myClass  {</p>\n\n<pre><code>public enum myEnum {\n    Option1("String1", 2), \n    Option2("String2", 2) \n    ;\n    String str;\n            int i;\n\n            myEnum(String str1, int i1) { this.str = str1 ; this.i1 = i }\n\n\n}\n</code></pre>\n'}, {'answer_id': 67057, 'author': 'Ryan Delucchi', 'author_id': 9931, 'author_profile': 'https://Stackoverflow.com/users/9931', 'pm_score': 1, 'selected': False, 'text': '<p>A Constant, of any type, can be declared by creating an immutable property that within a class (that is a member variable with the <code>final</code> modifier).  Typically the <code>static</code> and  <code>public</code> modifiers are also provided.</p>\n\n<pre><code>public class OfficePrinter {\n    public static final String STATE = "Ready";  \n}\n</code></pre>\n\n<p>There are numerous applications where a constant\'s value indicates a selection from an n-tuple (e.g. <em>enumeration</em>) of choices.  In our example, we can choose to define an Enumerated Type that will restrict the possible assigned values (i.e. improved <em>type-safety</em>):</p>\n\n<pre><code>public class OfficePrinter {\n    public enum PrinterState { Ready, PCLoadLetter, OutOfToner, Offline };\n    public static final PrinterState STATE = PrinterState.Ready;\n}\n</code></pre>\n'}, {'answer_id': 67310, 'author': 'Javamann', 'author_id': 10166, 'author_profile': 'https://Stackoverflow.com/users/10166', 'pm_score': 0, 'selected': False, 'text': "<p>One of the way I do it is by creating a 'Global' class with the constant values and do a static import in the classes that need access to the constant.</p>\n"}, {'answer_id': 67564, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<p>A single, generic constants class is a bad idea. Constants should be grouped together with the class they're most logically related to.</p>\n\n<p>Rather than using variables of any kind (especially enums), I would suggest that you use methods. Create a method with the same name as the variable and have it return the value you assigned to the variable. Now delete the variable and replace all references to it with calls to the method you just created. If you feel that the constant is generic enough that you shouldn't have to create an instance of the class just to use it, then make the constant method a class method.</p>\n"}, {'answer_id': 68068, 'author': 'Bradley Harris', 'author_id': 10503, 'author_profile': 'https://Stackoverflow.com/users/10503', 'pm_score': 2, 'selected': False, 'text': '<p>A good object oriented design should not need many publicly available constants.  Most constants should be encapsulated in the class that needs them to do its job.   </p>\n'}, {'answer_id': 68558, 'author': 'big_peanut_horse', 'author_id': 10720, 'author_profile': 'https://Stackoverflow.com/users/10720', 'pm_score': 3, 'selected': False, 'text': "<p>I prefer to use getters rather than constants.  Those getters might return constant values, e.g. <code>public int getMaxConnections() {return 10;}</code>, but anything that needs the constant will go through a getter.</p>\n\n<p>One benefit is that if your program outgrows the constant--you find that it needs to be configurable--you can just change how the getter returns the constant.</p>\n\n<p>The other benefit is that in order to modify the constant you don't have to recompile everything that uses it.  When you reference a static final field, the value of that constant is compiled into any bytecode that references it.</p>\n"}, {'answer_id': 68574, 'author': 'Tim Howland', 'author_id': 4276, 'author_profile': 'https://Stackoverflow.com/users/4276', 'pm_score': 1, 'selected': False, 'text': '<p>FWIW, a timeout in seconds value should probably be a configuration setting (read in from a properties file or through injection as in Spring) and not a constant.</p>\n'}, {'answer_id': 69187, 'author': 'Kevin Day', 'author_id': 10973, 'author_profile': 'https://Stackoverflow.com/users/10973', 'pm_score': 4, 'selected': False, 'text': "<p>Creating static final constants in a separate class can get you into trouble.  The Java compiler will actually optimize this and place the actual value of the constant into any class that references it.</p>\n\n<p>If you later change the 'Constants' class and you don't do a hard re-compile on other classes that reference that class, you will wind up with a combination of old and new values being used.</p>\n\n<p>Instead of thinking of these as constants, think of them as configuration parameters and create a class to manage them.  Have the values be non-final, and even consider using getters.  In the future, as you determine that some of these parameters actually should be configurable by the user or administrator, it will be much easier to do.</p>\n"}, {'answer_id': 4403167, 'author': 'chandrayya', 'author_id': 537066, 'author_profile': 'https://Stackoverflow.com/users/537066', 'pm_score': 1, 'selected': False, 'text': '<p>What is the difference</p>\n\n<p>1.</p>\n\n<pre><code>public interface MyGlobalConstants {\n    public static final int TIMEOUT_IN_SECS = 25;\n}\n</code></pre>\n\n<p>2.</p>\n\n<pre><code>public class MyGlobalConstants {\n    private MyGlobalConstants () {} // Prevents instantiation\n    public static final int TIMEOUT_IN_SECS = 25;\n}\n</code></pre>\n\n<p>and using \n<code>MyGlobalConstants.TIMEOUT_IN_SECS</code> wherever we need this constant. I think both are same.</p>\n'}, {'answer_id': 6486803, 'author': 'Lorand Bendig', 'author_id': 1050422, 'author_profile': 'https://Stackoverflow.com/users/1050422', 'pm_score': 2, 'selected': False, 'text': '<p>Based on the comments above I think this is a good approach to change the old-fashioned global constant class (having public static final variables) to its enum-like equivalent in a way like this:</p>\n\n<pre><code>public class Constants {\n\n    private Constants() {\n        throw new AssertionError();\n    }\n\n    public interface ConstantType {}\n\n    public enum StringConstant implements ConstantType {\n        DB_HOST("localhost");\n        // other String constants come here\n\n        private String value;\n        private StringConstant(String value) {\n            this.value = value;\n        }\n        public String value() {\n            return value;\n        }\n    }\n\n    public enum IntConstant implements ConstantType {\n        DB_PORT(3128), \n        MAX_PAGE_SIZE(100);\n        // other int constants come here\n\n        private int value;\n        private IntConstant(int value) {\n            this.value = value;\n        }\n        public int value() {\n            return value;\n        }\n    }\n\n    public enum SimpleConstant implements ConstantType {\n        STATE_INIT,\n        STATE_START,\n        STATE_END;\n    }\n\n}\n</code></pre>\n\n<p>So then I can refer them to like:</p>\n\n<pre><code>Constants.StringConstant.DB_HOST\n</code></pre>\n'}, {'answer_id': 8809578, 'author': 'albus.ua', 'author_id': 697116, 'author_profile': 'https://Stackoverflow.com/users/697116', 'pm_score': 4, 'selected': False, 'text': '<p>I use following approach:</p>\n\n<pre><code>public final class Constants {\n  public final class File {\n    public static final int MIN_ROWS = 1;\n    public static final int MAX_ROWS = 1000;\n\n    private File() {}\n  }\n\n  public final class DB {\n    public static final String name = "oups";\n\n    public final class Connection {\n      public static final String URL = "jdbc:tra-ta-ta";\n      public static final String USER = "testUser";\n      public static final String PASSWORD = "testPassword";\n\n      private Connection() {}\n    }\n\n    private DB() {}\n  }\n\n  private Constants() {}\n}\n</code></pre>\n\n<p>Than, for example, I use <code>Constants.DB.Connection.URL</code> to get constant.\nIt looks more "object oriently" as for me.</p>\n'}, {'answer_id': 12207932, 'author': 'wulfgarpro', 'author_id': 512994, 'author_profile': 'https://Stackoverflow.com/users/512994', 'pm_score': 0, 'selected': False, 'text': "<p><code>static final</code> is my preference, I'd only use an <code>enum</code> if the item was indeed enumerable.</p>\n"}, {'answer_id': 16565371, 'author': 'bincob', 'author_id': 1619065, 'author_profile': 'https://Stackoverflow.com/users/1619065', 'pm_score': 0, 'selected': False, 'text': "<p>I use <code>static final</code> to declare constants and go with the ALL_CAPS naming notation. I have seen quite a few real life instances where all constants are bunched together into an interface. A few posts have rightly called that a bad practice, primarily because that's not what an interface is for. An interface should enforce a contract and should not be a place to put unrelated constants in. Putting it together into a class that cannot be instantiated (through a private constructor) too is fine if the constant semantics don't belong to a specific class(es). I always put a constant in the class that it's most related to, because that makes sense and is also easily maintainable.</p>\n\n<p>Enums are a good choice to represent a range of values, but if you are storing standalone constants with an emphasis on the absolute value (eg. TIMEOUT = 100 ms) you can just go for the <code>static final</code> approach.</p>\n"}, {'answer_id': 38639581, 'author': 'Quinn Turner', 'author_id': 4400318, 'author_profile': 'https://Stackoverflow.com/users/4400318', 'pm_score': 0, 'selected': False, 'text': '<p>I agree with what most are saying, it is best to use enums when dealing with a collection of constants. However, if you are programming in Android there is a better solution: <a href="https://developer.android.com/reference/android/support/annotation/IntDef.html" rel="nofollow">IntDef Annotation</a>.</p>\n\n<pre><code>@Retention(SOURCE)\n@IntDef({NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST,NAVIGATION_MODE_TABS})\npublic @interface NavigationMode {}\npublic static final int NAVIGATION_MODE_STANDARD = 0;\npublic static final int NAVIGATION_MODE_LIST = 1;\npublic static final int NAVIGATION_MODE_TABS = 2;\n...\npublic abstract void setNavigationMode(@NavigationMode int mode);\n@NavigationMode\npublic abstract int getNavigationMode();\n</code></pre>\n\n<p>IntDef annotation is superior to enums in one simple way, it takes significantly less space as it is simply a compile-time marker. It is not a class, nor does it have the automatic string-conversion property.</p>\n'}, {'answer_id': 41526147, 'author': 'djangofan', 'author_id': 118228, 'author_profile': 'https://Stackoverflow.com/users/118228', 'pm_score': 2, 'selected': False, 'text': '<p>There is a certain amount of opinion to answer this.  To start with, constants in java are generally declared to be public, static and final. Below are the reasons:</p>\n\n<pre><code>public, so that they are accessible from everywhere\nstatic, so that they can be accessed without any instance. Since they are constants it\n  makes little sense to duplicate them for every object.\nfinal, since they should not be allowed to change\n</code></pre>\n\n<p>I would never use an interface for a CONSTANTS accessor/object simply because interfaces are generally expected to be implemented.  Wouldn\'t this look funny:</p>\n\n<pre><code>String myConstant = IMyInterface.CONSTANTX;\n</code></pre>\n\n<p>Instead I would choose between a few different ways, based on some small trade-offs, and so it depends on what you need:</p>\n\n<pre><code>1.  Use a regular enum with a default/private constructor. Most people would define \n     constants this way, IMHO.\n  - drawback: cannot effectively Javadoc each constant member\n  - advantage: var members are implicitly public, static, and final\n  - advantage: type-safe\n  - provides "a limited constructor" in a special way that only takes args which match\n     predefined \'public static final\' keys, thus limiting what you can pass to the\n     constructor\n\n2.  Use a altered enum WITHOUT a constructor, having all variables defined with \n     prefixed \'public static final\' .\n  - looks funny just having a floating semi-colon in the code\n  - advantage: you can JavaDoc each variable with an explanation\n  - drawback: you still have to put explicit \'public static final\' before each variable\n  - drawback: not type-safe\n  - no \'limited constructor\'\n\n3.  Use a Class with a private constructor:\n  - advantage: you can JavaDoc each variable with an explanation\n  - drawback: you have to put explicit \'public static final\' before each variable\n  - you have the option of having a constructor to create an instance\n     of the class if you want to provide additional functions related\n     to your constants \n     (or just keep the constructor private)\n  - drawback: not type-safe\n\n4. Using interface:\n  - advantage: you can JavaDoc each variable with an explanation\n  - advantage: var members are implicitly \'public static final\'\n  - you are able to define default interface methods if you want to provide additional\n     functions related to your constants (only if you implement the interface)\n  - drawback: not type-safe\n</code></pre>\n'}, {'answer_id': 44452756, 'author': 'davidxxx', 'author_id': 270371, 'author_profile': 'https://Stackoverflow.com/users/270371', 'pm_score': 2, 'selected': False, 'text': '<blockquote>\n  <p>What is the best way to implement constants in Java?</p>\n</blockquote>\n\n<p><strong>One approach that we should really avoid</strong> : using interfaces to define constants.<br></p>\n\n<p>Creating a interface specifically to declare constants is really the worst thing : it defeats the reason why interfaces were designed : defining method(s) contract.<br></p>\n\n<p>Even if an interface already exists to address a specific need, declaring the constants in them make really not sense as constants should not make part of the API and the contract provided to client classes.<br></p>\n\n<hr>\n\n<p><strong>To simplify, we have broadly 4 valid approaches</strong>.<br></p>\n\n<p>With <code>static final String/Integer</code> field :</p>\n\n<ul>\n<li>1) using a class that declares constants inside but not only.</li>\n<li>1 variant) creating a class dedicated to only declare constants.</li>\n</ul>\n\n<p>With <code>Java 5 enum</code> :</p>\n\n<ul>\n<li>2) declaring the enum in a related purpose class (so as a nested class).</li>\n<li>2 variant) creating the enum as a standalone class (so defined in its own class file).</li>\n</ul>\n\n<hr>\n\n<p><strong>TLDR : Which is the best way and where locate the constants ?</strong></p>\n\n<p><strong>In most of cases, the enum way is probably finer than the <code>static final String/Integer</code> way</strong> and personally I think that the <code>static final String/Integer</code> way should be used only if we have good reasons to not use enums.<br>\nAnd about where we should declare the constant values, <strong>the idea is to search whether there is a single existing class that owns a specific and strong functional cohesion with constant values. If we find such a class, we should use it as the constants holder</strong>. Otherwise, the constant should be associated to no one particular class.</p>\n\n<hr>\n\n<p><strong><code>static final String</code>/ <code>static final Integer</code> versus <code>enum</code></strong> </p>\n\n<p>Enums usage is really a way to strongly considered.<br>\nEnums have a great advantage over <code>String</code> or <code>Integer</code> constant field. <br>\nThey set a stronger compilation constraint. \nIf you define a method that takes the enum as parameter, you can only pass a enum value defined in the enum class(or null). <br>\nWith String and Integer you can substitute them with any values of compatible type and the compilation will be fine even if the value is not a defined constant in the <code>static final String</code>/ <code>static final Integer</code> fields. </p>\n\n<p>For example, below two constants defined in a class as <code>static final String</code> fields :</p>\n\n<pre><code>public class MyClass{\n\n   public static final String ONE_CONSTANT = "value";\n   public static final String ANOTHER_CONSTANT = "other value";\n   . . .\n}\n</code></pre>\n\n<p>Here a method that expects to have one of these constants as parameter :</p>\n\n<pre><code>public void process(String constantExpected){\n    ...    \n}\n</code></pre>\n\n<p>You can invoke it in this way :</p>\n\n<pre><code>process(MyClass.ONE_CONSTANT);\n</code></pre>\n\n<p>or </p>\n\n<pre><code>process(MyClass.ANOTHER_CONSTANT);\n</code></pre>\n\n<p>But no compilation constraint prevents you from invoking it in this way :</p>\n\n<pre><code>process("a not defined constant value");\n</code></pre>\n\n<p>You would have the error only at runtime and only if you do at a time a check on the transmitted value.</p>\n\n<p>With enum, checks are not required as the client could only pass a enum value in a enum parameter.<br></p>\n\n<p>For example, here two values defined in a enum class (so constant out of the box):</p>\n\n<pre><code>public enum MyEnum {\n\n    ONE_CONSTANT("value"), ANOTHER_CONSTANT(" another value");\n\n    private String value;\n\n    MyEnum(String value) {\n       this.value = value;\n    }\n         ...\n}\n</code></pre>\n\n<p>Here a method that expects to have one of these enum values as parameter :</p>\n\n<pre><code>public void process(MyEnum myEnum){\n    ...    \n}\n</code></pre>\n\n<p>You can invoke it in this way :</p>\n\n<pre><code>process(MyEnum.ONE_CONSTANT);\n</code></pre>\n\n<p>or </p>\n\n<pre><code>process(MyEnum.ANOTHER_CONSTANT);\n</code></pre>\n\n<p>But the compilation will never allow you from invoking it in this way :</p>\n\n<pre><code>process("a not defined constant value");\n</code></pre>\n\n<hr>\n\n<p><strong>Where should we declare the constants ?</strong></p>\n\n<p>If your application contains a single existing class that owns a specific and strong functional cohesion with the constant values, the 1) and the 2) appear more intuitive.<br>\nGenerally, it eases the use of the constants if these are declared in the main class that manipulates them or that has a name very natural to guess that we will find it inside.<br></p>\n\n<p>For example in the JDK library, the exponential and pi constant values are   declared in a class that declare not only constant declarations (<code>java.lang.Math</code>).</p>\n\n<pre><code>   public final class Math {\n          ...\n       public static final double E = 2.7182818284590452354;\n       public static final double PI = 3.14159265358979323846;\n         ...\n   }\n</code></pre>\n\n<p>The clients using mathematics functions rely often on the <code>Math</code> class.\nSo, they may find constants easily enough and can also remember where <code>E</code> and <code>PI</code> are defined in a very natural way.<br>    </p>\n\n<p>If your application doesn\'t contain an existing class that has a very specific and strong functional cohesion with the constant values, the 1 variant) and the 2 variant) ways appear more intuitive.<br>\nGenerally, it doesn\'t ease the use of the constants if these are declared in one class that manipulates them while we have also 3 or 4 other classes that manipulate them as much as and no one of these classes seems be more natural than others to host constant values.<br>\nHere, defining a custom class to hold only constant values makes sense.<br>\nFor example in the JDK library, the <code>java.util.concurrent.TimeUnit</code> enum is not declared in a specific class as there is not really one and only one JDK specific class that appear as the most intuitive to hold it :</p>\n\n<pre><code>public enum TimeUnit {\n    NANOSECONDS {\n      .....\n    },\n    MICROSECONDS {\n      .....\n    },\n    MILLISECONDS {\n      .....\n    },\n    SECONDS {\n      .....\n    },\n      .....\n}      \n</code></pre>\n\n<p>Many classes declared in <code>java.util.concurrent</code> use them :\n<code>BlockingQueue</code>, <code>ArrayBlockingQueue&lt;E&gt;</code>, <code>CompletableFuture</code>, <code>ExecutorService</code> , ... and really no one of them seems more appropriate to hold the enum.<br></p>\n'}, {'answer_id': 48186688, 'author': 'Blessed Geek', 'author_id': 140803, 'author_profile': 'https://Stackoverflow.com/users/140803', 'pm_score': 0, 'selected': False, 'text': '<p>It is <strong>BAD habit and terribly \nANNOYING practice</strong> to quote Joshua Bloch without understanding the basic ground-zero fundamentalism.</p>\n\n<p>I have not read anything Joshua Bloch, so either</p>\n\n<ul>\n<li>he is a terrible programmer</li>\n<li>or the people so far whom I find quoting him (Joshua is the name of a boy I presume) are simply using his material as religious scripts to justify their software religious indulgences.</li>\n</ul>\n\n<p>As in Bible fundamentalism all the biblical laws can be summed up by</p>\n\n<ul>\n<li>Love the Fundamental Identity with all your heart and all your mind</li>\n<li>Love your neighbour as yourself</li>\n</ul>\n\n<p>and so similarly software engineering fundamentalism can be summed up by</p>\n\n<ul>\n<li>devote yourself to the ground-zero fundamentals with all your programming might and mind</li>\n<li>and devote towards the excellence of your fellow-programmers as you would for yourself.</li>\n</ul>\n\n<p>Also, among biblical fundamentalist circles a strong and reasonable corollary is drawn</p>\n\n<ul>\n<li>First love yourself. Because if you don\'t love yourself much, then the concept "love your neighbour as yourself" doesn\'t carry much weight, since "how much you love yourself" is the datum line above which you would love others.</li>\n</ul>\n\n<p>Similarly, if you do not respect yourself as a programmer and just accept the pronouncements and prophecies of some programming guru-nath WITHOUT questioning the fundamentals, your quotations and reliance on Joshua Bloch (and the like) is meaningless. And therefore, you would actually have no respect for your fellow-programmers.</p>\n\n<p>The fundamental laws of software programming</p>\n\n<ul>\n<li>laziness is the virtue of a good programmer</li>\n<li>you are to make your programming life as easy, as lazy and therefore as effective as possible</li>\n<li>you are to make the consequences and entrails of your programming as easy, as lazy and therefore as effective as possible for your neigbour-programmers who work with you and pick up your programming entrails.</li>\n</ul>\n\n<h3>Interface-pattern constants is a bad habit ???</h3>\n\n<p>Under what laws of fundamentally effective and responsible programming does this religious edict fall into ?</p>\n\n<p>Just read the wikipedia article on interface-pattern constants (<a href="https://en.wikipedia.org/wiki/Constant_interface" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Constant_interface</a>), and the silly excuses it states against interface-pattern constants.</p>\n\n<ul>\n<li><p>Whatif-No IDE? Who on earth as a software programmer would not use an IDE? Most of us are programmers who prefer not to have to prove having macho aescetic survivalisticism thro avoiding the use of an IDE.</p>\n\n<ul>\n<li>Also - wait a second proponents of micro-functional programming as a means of not needing an IDE. Wait till you read my explanation on data-model normalization.</li>\n</ul></li>\n<li><p>Pollutes the namespace with variables not used within the current scope? It could be proponents of this opinion</p>\n\n<ul>\n<li>are not aware of, and the need for, data-model normalization</li>\n</ul></li>\n<li><p>Using interfaces for enforcing constants is an abuse of interfaces. Proponents of such have a bad habit of </p>\n\n<ul>\n<li>not seeing that "constants" must be treated as contract. And interfaces are used for enforcing or projecting compliance to a contract.</li>\n</ul></li>\n<li><p>It is difficult if not impossible to convert interfaces into implemented classes in the future. Hah .... hmmm ... ???</p>\n\n<ul>\n<li>Why would you want to engage in such pattern of programming as your persistent livelihood? IOW, why devote yourself to such an AMBIVALENT and bad programming habit ?</li>\n</ul></li>\n</ul>\n\n<p>Whatever the excuses, there is NO VALID EXCUSE when it comes to FUNDAMENTALLY EFFECTIVE software engineering to delegitimize or generally discourage the use of interface constants.</p>\n\n<p>It doesn\'t matter what the original intents and mental states of the founding fathers who crafted the United States Constitution were. We could debate the original intents of the founding fathers but all I care is the written statements of the US Constitution. And it is the responsibility of every US citizen to exploit the written literary-fundamentalism, not the unwritten founding-intents, of the US Constitution.</p>\n\n<p>Similarly, I do not care what the "original" intents of the founders of the Java platform and programming language had for the interface. What I care are the effective features the Java specification provides, and I intend to exploit those features to the fullest to help me fulfill the fundamental laws of responsible software programming. I don\'t care if I am perceived to "violate the intention for interfaces". I don\'t care what Gosling or someone Bloch says about the "proper way to use Java", unless what they say does not violate my need to EFFECTIVE fulfilling fundamentals.</p>\n\n<h3>The Fundamental is Data-Model Normalization</h3>\n\n<p>It doesn\'t matter how your data-model is hosted or transmitted. Whether you use interfaces or enums or whatevernots, relational or no-SQL, if you don\'t understand the need and process of data-model normalization.</p>\n\n<p>We must first define and normalize the data-model of a set of processes. And when we have a coherent data-model, ONLY then can we use the process flow of its components to define the functional behaviour and process blocks a field or realm of applications. And only then can we define the API of each functional process.</p>\n\n<p>Even the facets of data normalization as proposed by EF Codd is now severely challenged and severely-challenged. e.g. his statement on 1NF has been criticized as ambiguous, misaligned and over-simplified, as is the rest of his statements especially in the advent of modern data services, repo-technology and transmission. IMO, the EF Codd statements should be completely ditched and new set of more mathematically plausible statements be designed.</p>\n\n<p>A glaring flaw of EF Codd\'s and the cause of its misalignment to effective human comprehension is his belief that humanly perceivable multi-dimensional, mutable-dimension data can be efficiently perceived thro a set of piecemeal 2-dimensional mappings.</p>\n\n<h3>The Fundamentals of Data Normalization</h3>\n\n<p>What EF Codd failed to express.</p>\n\n<p>Within each coherent data-model, these are the sequential graduated order of data-model coherence to achieve.</p>\n\n<ol>\n<li>The Unity and Identity of data instances.\n\n<ul>\n<li>design the granularity of each data component, whereby their granularity is at a level where each instance of a component can be uniquely identified and retrieved.</li>\n<li>absence of instance aliasing. i.e., no means exist whereby an identification produces more than one instance of a component.</li>\n</ul></li>\n<li>Absence of instance crosstalk. There does not exist the necessity to use one or more other instances of a component to contribute to identifying an instance of a component.</li>\n<li>The unity and identity of data components/dimensions.\n\n<ul>\n<li>Presence of component de-aliasing. There must exist one definition whereby a component/dimension can be uniquely identified. Which is the primary definition of a component;</li>\n<li>where the primary definition will not result in exposing sub-dimensions or member-components that are not part of an intended component;</li>\n</ul></li>\n<li>Unique means of component dealiasing. There must exist one, and only one, such component de-aliasing definition for a component.</li>\n<li>There exists one, and only one, definition interface or contract to identify a parent component in a hierarchical relationship of components. </li>\n<li>Absence of component crosstalk. There does not exist the necessity to use a member of another component to contribute to the definitive identification of a component.\n\n<ul>\n<li>In such a parent-child relationship, the identifying definition of a parent must not depend on part of the set of member components of a child. A member component of a parent\'s identity must be the complete child identity without resorting to referencing any or all of the children of a child.</li>\n</ul></li>\n<li>Preempt bi-modal or multi-modal appearances of a data-model.\n\n<ul>\n<li>When there exists two candidate definitions of a component, it is an obvious sign that there exists two different data-models being mixed up as one. That means there is incoherence at the data-model level, or the field level.</li>\n<li>A field of applications must use one and only one data-model, coherently.</li>\n</ul></li>\n<li>Detect and identify component mutation. Unless you have performed statistical component analysis of huge data, you probably do not see, or see the need to treat, component mutation.\n\n<ul>\n<li>A data-model may have its some of its components mutate cyclically or gradually.</li>\n<li>The mode may be member-rotation or transposition-rotation.</li>\n<li>Member-rotation mutation could be distinct swapping of child components between components. Or where completely new components would have to be defined.</li>\n<li>Transpositional mutation would manifest as a dimensional-member mutating into an attribute, vice versa.</li>\n<li>Each mutation cycle must be identified as a distinct data-modal.</li>\n</ul></li>\n<li>Versionize each mutation. Such that you can pull out a previous version of the data model, when perhaps the need arise to treat an 8 year old mutation of the data model.</li>\n</ol>\n\n<p>In a field or grid of inter-servicing component-applications, there must be one and only one coherent data-model or exists a means for a data-model/version to identify itself.</p>\n\n<h3>Are we still asking if we could use Interface Constants? Really ?</h3>\n\n<p>There are data-normalization issues at stake more consequential than this mundane question. IF you don\'t solve those issues, the confusion that you think interface constants cause is comparatively nothing. Zilch.</p>\n\n<p>From the data-model normalization then you determine the components as variables, as properties, as contract interface constants.</p>\n\n<p>Then you determine which goes into value injection, property configuration placeholding, interfaces, final strings, etc.</p>\n\n<p>If you have to use the excuse of needing to locate a component easier to dictate against interface constants, it means you are in the bad habit of not practicing data-model normalization.</p>\n\n<p>Perhaps you wish to compile the data-model into a vcs release. That you can pull out a distinctly identifiable version of a data-model.</p>\n\n<p>Values defined in interfaces are completely assured to be non-mutable. And shareable. Why load a set of final strings into your class from another class when all you need is that set of constants ??</p>\n\n<p>So why not this to publish a data-model contract? I mean if you can manage and normalize it coherently, why not? ...</p>\n\n<pre><code>public interface CustomerService {\n  public interface Label{\n    char AssignmentCharacter = \':\';\n    public interface Address{\n      String Street = "Street";\n      String Unit= "Unit/Suite";\n      String Municipal = "City";\n      String County = "County";\n      String Provincial = "State";\n      String PostalCode = "Zip"\n    }\n\n    public interface Person {\n      public interface NameParts{\n        String Given = "First/Given name"\n        String Auxiliary = "Middle initial"\n        String Family = "Last name"\n      }\n    }\n  }\n}\n</code></pre>\n\n<p>Now I can reference my apps\' contracted labels in a way such as</p>\n\n<pre><code>CustomerService.Label.Address.Street\nCustomerService.Label.Person.NameParts.Family\n</code></pre>\n\n<p>This confuses the contents of the jar file? As a Java programmer I don\'t care about the structure of the jar.</p>\n\n<p>This presents complexity to osgi-motivated runtime swapping ? Osgi is an extremely efficient means to allow programmers to continue in their bad habits. There are better alternatives than osgi.</p>\n\n<p>Or why not this? There is no leakage of of the private Constants into published contract. All private constants should be grouped into a private interface named "Constants", because I don\'t want to have to search for constants and I am too lazy to repeatedly type "private final String".</p>\n\n<pre><code>public class PurchaseRequest {\n  private interface Constants{\n    String INTERESTINGName = "Interesting Name";\n    String OFFICIALLanguage = "Official Language"\n    int MAXNames = 9;\n  }\n}\n</code></pre>\n\n<p>Perhaps even this:</p>\n\n<pre><code>public interface PurchaseOrderConstants {\n  public interface Properties{\n    default String InterestingName(){\n       return something();\n    }\n    String OFFICIALLanguage = "Official Language"\n    int MAXNames = 9;\n  }\n}\n</code></pre>\n\n<p>The only issue with interface constants worth considering is when the interface is implemented.</p>\n\n<p>This is not the "original intention" of interfaces? Like I would care about the "original intention" of the founding fathers in crafting the US Constitution, rather than how the Supreme Court would interpret the written letters of the US Constitution ???</p>\n\n<p>After all, I live in the land of the free, the wild and home of the brave. Be brave, be free, be wild - use the interface. If my fellow-programmers refuse to use efficient and lazy means of programming, am I obliged by the golden rule to lessen my programming efficiency to align with theirs? Perhaps I should, but that is not an ideal situation.</p>\n'}]
['https://Stackoverflow.com/questions/66066', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1797/']