Let me prove you that why we need to use as much enum as possible instead of public static final String.
Constant.java
public class Constant
{
public static final String TEST_CONST_STRING = "TestConstString";
}
EnumConstant.java
public enum EnumConstant
{
TEST_CONST_STRING("EnumTestConstString");
String str;
EnumConstant(String str)
{
this.str = str;
}
public String getValue()
{
return str;
}
}
Consumer.java
public class Consumer
{
public static void main(String[] args)
{
System.out.println(Constant.TEST_CONST_STRING);
System.out.println(EnumConstant.TEST_CONST_STRING.getValue());
}
}
Assume all the 3 java files are present in the same directory. Now do the following:
a) Run javac Constant.java EnumConstant.java Consumer.java
b) Run java Consumer
Now obviously TestConstString and EnumTestConstString gets printed in the console.
c) Now change the "TestConstString" in Constant.java to "TestConstStringChanged" and "EnumTestConstString" to "EnumTestConstStringChanged".
d) Run javac Constant.java EnumConstant.java. Don't compile Consumer.java.
e) Run java Consumer.
Now you can see that TestConstString and EnumTestConstStringChanged gets printed in the console.
TestConstStringChanged doesn't get printed.
Reason: When we change any value pointed by public static final String, then we need to recompile all the files which depend on this string. In case of Enum, we don't need to compile the dependent files.
Constant.java
public class Constant
{
public static final String TEST_CONST_STRING = "TestConstString";
}
EnumConstant.java
public enum EnumConstant
{
TEST_CONST_STRING("EnumTestConstString");
String str;
EnumConstant(String str)
{
this.str = str;
}
public String getValue()
{
return str;
}
}
Consumer.java
public class Consumer
{
public static void main(String[] args)
{
System.out.println(Constant.TEST_CONST_STRING);
System.out.println(EnumConstant.TEST_CONST_STRING.getValue());
}
}
Assume all the 3 java files are present in the same directory. Now do the following:
a) Run javac Constant.java EnumConstant.java Consumer.java
b) Run java Consumer
Now obviously TestConstString and EnumTestConstString gets printed in the console.
c) Now change the "TestConstString" in Constant.java to "TestConstStringChanged" and "EnumTestConstString" to "EnumTestConstStringChanged".
d) Run javac Constant.java EnumConstant.java. Don't compile Consumer.java.
e) Run java Consumer.
Now you can see that TestConstString and EnumTestConstStringChanged gets printed in the console.
TestConstStringChanged doesn't get printed.
Reason: When we change any value pointed by public static final String, then we need to recompile all the files which depend on this string. In case of Enum, we don't need to compile the dependent files.