Enum vs static final String

I was going to use static final Strings as enumerated constants in my application, but would like to see if I should be using enums instead.
In terms of efficiency, if I have, say, 5 enumerated elements, will only one copy of the enumerated element be in memory, like a static final String? So regardless of how many times I refer to it, all references point to the same instance (I'm not sure if what I just said even makes sense in the context of enums, but perhaps you could clarify).
Are there any reasons why for enumerated constants that are known at development time, why static final Strings (or static final anything, for that matter) should be used instead of enums if you're using JDK 1.5?
Thanks.

In terms of efficiency, if I have, say, 5 enumerated elements, will only one copy of
the enumerated element be in memory, like a static final String?I don't know if it addesses your concerns, but the the Java Language Specification says this about enums: "It is a compile-time error to attempt to explicitly instantiate an enum type (�15.9.1). The final clone method in Enum ensures that enum constants can never be cloned, and the special treatment by the serialization mechanism ensures that duplicate instances are never created as a result of deserialization. Reflective instantiation of enum types is prohibited. Together, these four things ensure that no instances of an enum type exist beyond those defined by the enum constants." (http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.9)
As for the problems of memory usage, how big are these strings anyway?
The advantages of using enums over static final strings are discussed in the "technotes" accompanying 1.5 http://java.sun.com/javase/6/docs/technotes/guides/language/enums.html They list the following as problems with the static final "antipattern"
  * It is not typesafe (methods that expect one of your constants can be sent any old string)
  * There is no name space - so you must continually be sure that your constants don't have names that may be confused
  * Brittleness. Your strings will be compiled into the clients that use them. Then later you add a new constant...
�  * Printed values will be uninformative. Perhaps less of a problem for Strings, but, still, simply printing the string will leave its semantic significance obscure.

Similar Messages

  • Constant values (public static final String) are not shown??

    This has already been posted and no body answered. Any help is appreciated.
    In web service is it possible to expose the Constants used in the application. Let say for my web service I need to pass value for Operation, possible values for this are (add, delete, update). Is it possible expose these constant values(add, delete, update) visible to client application accesssing the web service.
    Server Side:
    public static final String ADD = "ADDOPP";
    public static final String DELETE = "DELETEOPP";
    public static final String UPDATE = "UPDATEOPP";
    client Side: mywebserviceport.setOperation( mywebservicePort.ADD );
    thanks
    vijay

    Sure, you can use JAX-WS and enums.
    For example on the server:
    @WebService
    public class echo {
    public enum Status {RED, YELLOW, GREEN}
    @WebMethod
    public Status echoStatus(Status status) {
    return status;
    on the client you get.
    @WebService(name = "Echo", wsdlLocation ="..." )
    public interface Echo {
    @WebMethod
    public Status echoStatus(
    @WebParam(name = "arg0", targetNamespace = "")
    Status arg0);
    @XmlEnum
    public enum Status {
    GREEN,
    RED,
    YELLOW;
    public String value() {
    return name();
    public static Status fromValue(String v) {
    return valueOf(v);
    }

  • 'private static final String' constants vs inline constants

    Other than source code readability and maintainability, is there any runtime benefit from declaring String constants as 'private static final' in your code? Does this effect the way the String is stored in memory in the constant pool?
    Thanks, Kevin

    I guess my question really is, is this String declared inline:
    System.out.println("some constant");treated any different internally in memory at runtime compared with this:
    System.out.println(SOME_CONSTANT);
    private static final String SOME_CONSTANT = "some constant";Since both Strings end up in the Constant Pool, how is declaring it 'static final' of any benefit in terms of performance?

  • Static final String

    Any body know hat this following code means?
    public static final String JAVA_HOME = System.getProperty("java.home");
    public static final String CURRENT_DIR = System.getProperty("user.dir");
    thanks you

    It defines two object variables (JAVA_HOME and CURRENT_DIR), that are:
    static - there's only ever one of them, no matter how many times the class they are in is instantiated.
    final - cannot be changed.
    public - available to all other classes outside of the current class.
    The two variables are then assigned to system properties, for a list of system properties and their meanings look here:
    http://java.sun.com/docs/books/tutorial/essential/system/properties.html
    A 'static final' variable is called a 'constant'. It is very useful when you want to define a variable and keep it that way. For example, if you wrote a program that worked out the area of a circle, you might want a static final variable PI = 3.14159.
    Constant variables are usually defined in uppercase. This is not forced, but it's good practice.

  • Public static final Comparator String CASE_INSENSITIVE_ORDER

    in this declaration..
    public static final Comparator<String> CASE_INSENSITIVE_ORDER
    what does <String> mean?
    thanks!

    what does the Comparator do. Look at the API and you would see the following description about the compare method.
    public int compare(Object o1,
    Object o2)Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
    The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y. (This implies that compare(x, y) must throw an exception if and only if compare(y, x) throws an exception.)
    The implementor must also ensure that the relation is transitive: ((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0.
    Finally, the implementer must ensure that compare(x, y)==0 implies that sgn(compare(x, z))==sgn(compare(y, z)) for all z.
    It is generally the case, but not strictly required that (compare(x, y)==0) == (x.equals(y)). Generally speaking, any comparator that violates this condition should clearly indicate this fact. The recommended language is "Note: this comparator imposes orderings that are inconsistent with equals."
    Now your question is about what <String> is in your declaration. It is the type of the objects which are going to be compared.

  • Automatic generation of enum members from name Strings

    I have a program in which I read information about Target objects from a text file. I store some of this information as an enum property of the target.
    }else if (itemKey.equalsIgnoreCase( "type")) {
    currentTarget.descriptor= itemValue;
    currentTarget.type = Target.getTargetType(currentTarget.descriptor);And elsewhere in the program I do the file reading and assignment of instance variables:
    class Target{
    enum TargetType {COUGH_DROP, RICE_CRACKER, PEPTO_BISMOL,UNDETERMINED};
    String descriptor;
    TargetType type;
    returns the target' s type as specified by a descriptor
    public static TargetType getTargetType (String descriptorString) {
    if (descriptorString.equals( "rice cracker")) {
    return (TargetType.RICE_CRACKER);
    } else if (descriptorString.equals ("cough drop")){
    return (TargetType.COUGH_DROP);
    } else if (descriptorString.equals ("Pepto-Bismol")){
    return (TargetType.PEPTO_BISMOL);
    } else {
    return (TargetType.UNDETERMINED);
    } I would like to be able to automatically generate the members of the TargetType enum from a list of strings as opposed to needing a method such as getTargetType above. Is this possible?
    Regards,
    Joe
    PS: I completely apologize for the appearance of the code above. I have no idea why this editor removed my indentation and added HTML markers. (I copied the code from a text editor, pasted into this editor, selected the code sections and clicked on the code button )
    PPS I now see that after a couple of switches between preview and rich text in the HTML markers have disappeared. WTF?

    I'm very curious to understand why one would like to create enum constants at run time? How can therse enums be used in the code that is not created at runtime? What are you really trying to achieve
    I know you marked your question as answered, but... you may have a look at the code below. It is a very very simple example of how to map real life descriptions (at runtime) to pre-existing enums. I didn't test it, but for all I know it should just work. Does this solve the problem that you are experiencing?
    import java.util.HashSet;
    import java.util.Set;
    public enum TargetType {
        RICE_CRACKER("C:/Descriptions/RiceCrackers.txt"),
        COUGH_DROP("C:/Descriptions/CouphDrops.txt"),
        PEPTO_BISMOL("C:/Descriptions/PeptoBismol.txt"),
        UNDETERMINED("C:/Descriptions/Empty.txt"),
        public static TargetType getType(String description) {
         for (TargetType targetType : TargetType.values()) {
             if (targetType.contains(description)) {
              return targetType;
         return UNDETERMINED;
        private final String fileName;
        private Set<String> descriptions = null;
        private TargetType(String fileName) {
         this.fileName = fileName;
        private boolean contains(String description) {
         if (descriptions == null) {
             descriptions = new HashSet<String>();
              * Populate descriptions from fileName.
         return descriptions.contains(description);
    }Piet

  • Instantiation of static final objects

    Is there a problem with coding the following?:
    class A {
    public static final A static_final_a_obj = new A ( B.static_final_b_obj );
    private B b;
    public A ( B b ) {
    this.b = b;
    class B {
    public static final B static_final_b_obj = new B ( A.static_final_a_obj );
    private A a;
    public B ( A a ) {
    this.a = a;
    I put log messages in each of the constructors to see if it would cause an infinite loop, but it doesn't seem to. The question is 'why'.. :) How can either of the static final objects ever be fully instantiated?

    Exactly. It is not executed infinitely.
    class A {
    public static final A static_final_a_obj = new A ( B.static_final_b_obj );
    private B b;
    public A ( B b ) {
    System.out.println(" A Cons");
    this.b = b;
    public static void main(String args[]) {
         System.out.println("A");
    Output:
    B Cons
    A Cons
    A
    class B {
    public static final B static_final_b_obj = new B ( A.static_final_a_obj );
    private A a;
    public B ( A a ) {
    System.out.println(" B Cons");
    this.a = a;
    public static void main(String args[]) {
         System.out.println("B");
    Output:
    A Cons
    B Cons
    B
    Edited by: prajeshps on Sep 18, 2007 1:51 PM

  • ERROR: serializable class HelloComponent does not declare a static final

    Hi everyone! I'm sorry but I'm a newbie to Java and I'm having some, I assume, basic problems learning to compile and run with javac. Here is my code:
    import javax.swing.* ;
    import java.awt.* ;
    public class MyJava {
    * @param args
    public static void main(String[] args)
    // TODO Auto-generated method stub
    JFrame frame = new JFrame( "HelloJava" ) ;
    HelloComponent hello = new HelloComponent() ;
    frame.add( hello ) ;
    frame.setSize( 300, 300 ) ;
    frame.setVisible( true ) ;
    class HelloComponent extends JComponent
    public void paintComponent( Graphics g )
    g.drawString( "Hello Java it's me!", 125, 95 ) ;
    And here is the error:
    1. WARNING in HelloJava.java
    (at line 20)
    class HelloComponent extends JComponent {
    ^^^^^^^^^^^^^^
    The serializable class HelloComponent does not declare a static final serialVersionUID field of type long
    ANY HELP WOULD BE GREAT! THANKS! =)

    Every time I extend GameLoop, it gives me the warning
    serializable class X does not declare a static final serialVersionUID field of type long
    This is just a warning. You do not need to fix this because the class you are writing will never be serialized by the gaming engine. If you really want the warning to go away, add the code to your class:
    static final long serialVersionUID=0;

  • Help with public static final List

    I'm having a block here... I want to have a constant List, but I can't figure out how to do it so it actually contains the values I want. It's going to be a list of strings about 40 elements long. Obviously, if I didn't need the final, I'd just do List.add( ), but I need to do it right in the constructor. Thanks for the help.

    I guess the problem could be reworded, If I wantedto
    put this in a class that would never getinstantiated
    how would I initialize the List?You use a static intializer.Ah. I didn't get that out of the question. Thanks for the help.
    But here's an example:public class Foo {  
        static final java.util.List<String> list = new java.util.ArrayList<String>();
            list.add("one");
            list.add("two");
            list.add("three");
            // etc.
    }

  • Alpha compuler cant compile enums or static imports?!?

    Pardon me if this is the wrong place to ask this question but I couldnt find any forums specific to CAP program members:
    When trying to compile enums and static imports that work with the public prototype compiler, I get the following errors:
    C:\dev\hcj\tiger\src>c:\j2sdk1.5.0\bin\javac -version oreilly/hcj/tiger/*.java
    javac 1.5.0-beta
    oreilly/hcj/tiger/EnumAttach.java:18: 'class' or 'interface' expected
    public abstract enum EnumAttach {
                    ^
    oreilly/hcj/tiger/EnumAttach.java:35: 'class' or 'interface' expected
    ^
    oreilly/hcj/tiger/ErrorLevel.java:20: 'class' or 'interface' expected
    public enum ErrorLevel {
           ^
    oreilly/hcj/tiger/ErrorLevel.java:31: 'class' or 'interface' expected
    ^
    oreilly/hcj/tiger/ForEach.java:49: ';' expected
                    for (String person: importantPeople) {
                                      ^
    oreilly/hcj/tiger/ForEach.java:55: illegal start of expression
            ^
    oreilly/hcj/tiger/ForEach.java:81: ';' expected
                    for (String person: people) {
                                      ^
    oreilly/hcj/tiger/ForEach.java:87: illegal start of expression
            ^
    oreilly/hcj/tiger/StaticImports.java:15: <identifier> expected
    import static StatusColors.*;
           ^
    oreilly/hcj/tiger/StaticImports.java:15: '.' expected
    import static StatusColors.*;
                                ^
    oreilly/hcj/tiger/StaticImports.java:16: <identifier> expected
    import static java.lang.Math.*.
           ^
    oreilly/hcj/tiger/StaticImports.java:21: '.' expected
    public class StaticImports {
           ^
    12 errorsIs there something I am doing wrong or is this known bug?

    Use the compiler flag -source 1.5

  • Static Final boolean

    Ok, I am hoping someone can explain this to me. I have defined a static final boolean in a class:
    public static final boolean TEST_MODE = false;
    And in another class I use it:
    public void serverRequest(String url, String postData) throws RequestException {
    if (activeRequest == null) {
    *     if(ManagerRootPanel.TEST_MODE)*
    *          url = ManagerRootPanel.TEST_URL + url;*
    RequestBuilder builder = new RequestBuilder(
    postData == null ? RequestBuilder.GET : RequestBuilder.POST, url);
    lastRequestURL = url;
    activeRequest = builder.sendRequest(postData, this);
    When running the if statement is always executed, even when the boolean is compiled as false.
    *     if(ManagerRootPanel.TEST_MODE)*
    *          url = ManagerRootPanel.TEST_URL + url;*
    What am I missing?
    When I use:
    *     if(ManagerRootPanel.TEST_MODE == true)*
    *          url = ManagerRootPanel.TEST_URL + url;*
    it behaves according to my expectations.
    Wes
    Edited by: Wesley_Sonner on Sep 11, 2008 8:04 AM

    Wesley_Sonner wrote:
    Ok, I am hoping someone can explain this to me. I have defined a static final boolean in a class:
    public static final boolean TEST_MODE = false;
    And in another class I use it:
    public void serverRequest(String url, String postData) throws RequestException {
    if (activeRequest == null) {
    *     if(ManagerRootPanel.TEST_MODE)*
    *          url = ManagerRootPanel.TEST_URL + url;*
    RequestBuilder builder = new RequestBuilder(
    postData == null ? RequestBuilder.GET : RequestBuilder.POST, url);
    lastRequestURL = url;
    activeRequest = builder.sendRequest(postData, this);
    When running the if statement is always executed, even when the boolean is compiled as false.
    *     if(ManagerRootPanel.TEST_MODE)*
    *          url = ManagerRootPanel.TEST_URL + url;*
    What am I missing?
    When I use:
    *     if(ManagerRootPanel.TEST_MODE == true)*
    *          url = ManagerRootPanel.TEST_URL + url;*
    it behaves according to my expectations.
    Wes
    Edited by: Wesley_Sonner on Sep 11, 2008 8:04 AMPlease use code tags (hit the "code" button up there) when posting code - it makes it much easier to read.
    From what I can see your problem might be out-of-sync class files. Delete all class files, recompile, and then see if you get the behavior you're expecting.

  • Overloading a static final variable

    This is a question from a book. I am not sure of overloading a constructor with a static final variable. Here is the class
    public class Pizza{
    private static final double cost_price = 10.0;
    String topping;
    double price;
    }next, the question wanted me to create a constructor to override the topping and the price of the original constructor so i did
    public Pizza(String t, double p){
    topping = t;
    price = p;
    }Next it wants me to override the constructor another time only by receiving one parameter which is the topping by calling the above constructor but instantiate the price to the constant price which is the final static variable.
    public Pizza(String t){
    cost_price = p;
    this(t, p);
    }I dont know if the above solution that i did is correct as it maybe have some correction to be made because of the static final variable or the above code does not work. Please help me to verify thank you

    Sorry but what does it means? Do you have any
    solution? I would appreciate it .The last one should look like this:
    public Pizza(String t){
       this(t, cost_price);
    }

  • Static final

    I need to share several objects among all instances, so I mark them as static. As far as these variables should be initialized only once they must be final as well. The problem is that I can't use static initializer, because these final static objects are constructed by 2nd class.
    class Y {
         private static final var1;
         private static final var2;
         Y() {}
         static void useVars() { ... }
         void useVars() { ... }
    class Main {
         public static void main(String[] args) {
              v1 = getVar1();
              v2 = getVar2();
              initClassY(v1, v2); // initializing static final vars for Y
    }

    You can use blank finals. This allows one to declare
    a final without initializing it.This is correct.
    The catch is you must initialize it before you use it.This is true, but not exact.
    Actually, you must initialize it in the constructor
    The following will not compile :
    public MyClass{
       final int BLANK_FINAL;
       public MyClass(int arg1){
          setBF(arg1);
       private void setBF(int arg1){
          BLANK_FINAL = arg1 * 200 + 86; //compiler error

  • Static final modifier

    Is there any performace improvement if i declare a variable as static final? Especially for the two cases below.
    for example
    case 1
    private static final SQL_QUERY = "select .......";
    PreparedStatement ps=con.prepareStatement(SQL_QUERY);
    case 2
    PreparedStatement ps=con.prepareStatement("select .......");Is there any performance improvement for case 1over case 2

    Performance improvement? I seriously doubt it.
    If your query is in fact static and final, it should be declared as such. But as you're creating a prepared statement with it, which I assume you will use multiple times, it will get used only once anyway.
    In any case, evaluating the query itself is going to take a million times longer than declaring a String.

  • Static Final Long Results in RMIC Failure

    I have a variable in my remote interface:
    public static final Long ID = new Long("0");Which causes an RMIC failure with the following error:
    ID is not a valid primitive or String constant.So my question is, why must a static final variable be a primitive or a String?
    Thanks,
    toby

    I couldn't reproduce your case maybe you could post more info. Here is what I did: I created a remote interface with a Long declaration like your's. I created an implementation of that remote interface and compiled and rmic'ed them with noe errors, here are the source files:
    package junk;
    import java.rmi.*;
    public interface RIntf extends Remote {
        public static final Long ID = new Long("O");
        public String hello() throws RemoteException;
    package junk;
    import java.rmi.*;
    import java.rmi.server.*;
    public class RImpl extends UnicastRemoteObject implements RIntf {
        public RImpl() throws RemoteException {
        public String hello() throws RemoteException {
         System.err.println("junk");
         return "junk";
    }After javac'ing these two source files I ran rmic on junk.RImpl to produce the stubs and skeletons without any issue. Let me know if this is similar to your issue. By the way, there is an RMI specific forum located here: http://forum.java.sun.com/forum.jsp?forum=58

Maybe you are looking for

  • Typical Requirement in File Adapter

    Hi All,           My scenario is File to Proxy. Now scenario to pick up the File (at sender) is like this: There is a file pick up from FTP Server daily. We will have two files on FTP server.First file is a blank file , which we call a FLAG File. Sec

  • IN Operator in Forms

    IN operator in forms Hi, In the Forms I'm declaring a cursor and the where clause has IN operator like.. declare cursor cur is select... where name in (:global.var_temp); --:global.var_temp = 'TOM','HARRY','SANDY' begin end; :global.var_temp is list

  • Best way to get "fresh" new battery for PBG4?

    I need to buy my third battery for my 12" PBG4 (first two not recalled). Anyway, aren't some batteries fresher than others and, if so, how can I be ensured that I'm buying the freshest battery possible. I will have spent almost $300 for batteries and

  • POF & fromBinary

    Hi, I am in the process of making all my Java objects EvolvablePortableObject. I was using Externalizable, but from what i can tell, serializing with POF creates a smaller memory footprint and appears to be new new preferred way to store objects in a

  • Incorrect e-mail-adresses of Workspaces in GAL

    Hello I Have a problem with Outlook Connector: I have Oracle Connector 10_12_00 Installed and Microsoft Outlook 2000 mail client. When I open Oracle Global Address List (GAL) in Outlook, e-mail addresses of workspaces are displayed incorrect there, l