'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?

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);
    }

  • 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.

  • 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.

  • 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 buffer passed into FilterOutputStream.write(byte[])

    Greetings,
    My team is using a custom subclass of FilterOutputStream to XOR some bytes with a key before writing them to an underlying OutputStream. We have never had problems with it until we started testing with Java 1.4.x -- where we noticed that some optimizations had been made to GZIPOutputStream to write the GZIP header out at once using a static final buffer to hold the header.
    The problem seems to be that this header, although marked as static final, can still be changed when it is passed to our custom FilterOutputStream's write(byte[] b) method. For speed, we are XORing the bytes in place in the byte[] and then writing it directly back out. So every time we write the header with the same key, the static final byte[] that holds the header in GZIPOutputStream changes from its XORed to cleartext equivalent, and back.
    My question is this: should this be considered a bug in the SDK, or a bug in our code? Maybe I'm looking in the wrong place, but I can't find any documentation that specifies what can and can't be done with a byte[] that is passed into the write(byte[]) method of an OutputStream.
    Any input is appreciated.
    Regards,
    Mike Pontillo

    Mike,
    Need some code here to clarify. Are you saying that
    the original final static (constant) changes?
    You've got to be careful when you talk about passing a
    byte[], which can't be done, of course. You are
    passing a reference to a byte[]. Using the reference,
    the bytes can be copied. There aren't any restrictions
    on what can be done to the copy.
    and also, if you have final array, then only that arrays'
    reference is final, but the content of array may change
    as well as when that array wasn't static.Yes, I understand this. Thank you for your replies. FilterOutputStream.write(byte[]) of course takes a reference to a byte[]. We are overloading this to be something like:
    public void write(byte[] b) {
       for(int i = 0 ; i < b.length ; i++) {
          b[i] = foo(b);
    out.write(b);
    i.e. we modify the array inside the method rather than making a copy and writing out the copy.
    This hasn't been a problem until Java 1.4.x -- now GZIPOutputStream passes a private static final byte[] (reference of course) into write(byte[]) in OutputStream. So when our overloaded write(byte[]) method gets called in FilterOutputStream and code similar to the above runs, the private static final reference to a byte[] is overwritten in the java.util.zip.GZIPOutputStream class. This was a change sometime between 1.3 and 1.4, I believe. From the J2SDK 1.4.1_02 source:
         * Writes GZIP member header.
        private final static byte[] header = {
            (byte) GZIP_MAGIC,                // Magic number (short)
            (byte)(GZIP_MAGIC >> 8),          // Magic number (short)
            Deflater.DEFLATED,                // Compression method (CM)
            0,                                // Flags (FLG)
            0,                                // Modification time MTIME (int)
            0,                                // Modification time MTIME (int)
            0,                                // Modification time MTIME (int)
            0,                                // Modification time MTIME (int)
            0,                                // Extra flags (XFLG)
            0                                 // Operating system (OS)
        private void writeHeader() throws IOException {
            out.write(header);
        }As you can see, they are passing a private static final reference to a byte array into somebody's untrusted method (ours). =)
    Due to this issue we have to change our code so that it makes a copy of these bytes rather than changing them in the method. Now I'm wondering if this should be considered a bug in Java or not -- does changing bytes like this violate the general contract of an Input/Output stream? It at least seems like a bad idea for encapsulation purposes since anyone can change these bytes in the GZIPOutputStream class. We had previously assumed that if they were writing these bytes to an output stream they didn't care about them any more, which is the case 99.9% of the time in our experience.

  • 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.

  • Why a Constant has to be of type Static final  rather than final?

    Hi,
    I struck up with a basic doubt
    Why a Constant has to be of type Static final rather than final?
    Hoping for quick reply
    Venu.

    Hi,
    I struck up with a basic doubt
    Why a Constant has to be of type Static final rather
    than final?It doesn't have to be, but it usually makes more sense for it to be static (associated with the class) than non-static (associated with the instance). If every instance of the class will have the same value for that variable--whether it's final and a constant or not--it makes sense to make it static. There's no need for multiple copies of the same value. (And in the case of non-final variables, it can lead to incorrect program behavior if it's not static.) If each instance of the class could potentially have a different value for that variable, then it has to be non-static.

  • Will declaring primitives as static final (constants) conserve memory?

    I wrote a code
    int a = flag?1:0;on which my supervisor commented that 1 and 0 should be replaced by SomeInterface.ONE (=1) and SomeInterface.ZERO (=0) respectively. The reason he gave was that since constants are static so it will conserve memory.
    Is this really true?

    First of all, this Interface for Constants anti-pattern is widely derided.
    Secondly, one of the reasons it was used in the first place was readability, not performance, and in that case constants that pertain to the meaning of that 1 and 0, and not the values, might have been understandable (e.g. SomeInterface.TRUE = 1 and SomeInterface.FALSE = 0), but definately not ONE and ZERO.
    Thirdly, memory use is the same as public static final variables (as interface constants are), have their value compiled directly into the class using them, at the point where it used, so whether a constant is used, or a literal value, the space that that class definition uses is the same. In addition, there is then an interface definition that also has those values so the memory use is more, in end effect. And, regardless, that memory space is not on the heap, which is the memory space you will be most interested in, so it has no noticeable effect on memory space either way.

  • 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.

  • Static private void main(String[]) works (?!)

    Did anyone knew that?
    try yourself!!
    public class Foo {
    static private void main (String[] bla) {
       //anything
    }there's even a bug!! And Sun choose not fix it:
    http://developer.java.sun.com/developer/bugParade/bugs/4252539.html
    I'd like to hear what you folks think about this...
    IMO: fuc* encapsulation!

    No, I haven't done the certification exam and I have no plans to. But the answer to that question isstatic public void main (String[] bla)and the fact that other versions happen to work doesn't matter either theoretically or practically. Bugs that appear in certain implementations of Java shouldn't matter.

  • Private static void main(String args[]) ... ?????

    even if the main method is declared
    private static void main(String args[])
    //Code Here
    it works fine..can somebody explain the reason behind?

    hi rkippen
    so u mean, since the JVM is calling the main it can
    break all kinds of access specifiers to any class..am
    i right?
    This could be the case.
    However, I tried using 1.4.1 with no development environment (just java.exe) and it gave the following error:
    C:\>java MainTest
    Main method not public.
    So, your development environment might be the cause (e.g. what you use to program your code (e.x. JBuilder)), or the Java version.
    Your development environment might be using reflection to get around Java accessibility checks. For debugging purposes, it is possible to use reflection to obtain refereneces to private methods/fields and invoke those methods and access those fields.
    E.g.
    Vector v = new Vector();
    Field f = v.getClass().getDeclaredField("elementCount");
    f.setAccessible(true); // this is the trick
    f.set(v, new Integer(100));In the presence of a security manager, the setAccessible method will fire a "suppressAccessChecks" permission check.

  • Is the instance fields have private accessibility in String class?

    Is the instance fields have private accessibility in an immutable class, such as the String class?
    also Could any one answer the following question,
    (This is the question I got in written exam for job recruitment)
    "Invoking a method can represent a significant amount of overhead in a program; as such, some compilers will perform an optimization called "method inlining." This optimization will remove a method call by copying the code inside the method into the calling method."
    Referring to the text above, which one of these statements is true?
    Choice 1 The performance benefits should be balanced against the increased chance of a RuntimeException.
    Choice 2 It allows the use of getter and setter methods to execute nearly as fast as direct access to member variables.
    Choice 3 This optimization will only occur if the relevant methods are declared volatile.
    Choice 4 The developer of inlined methods must copy and paste the code that is to be inlined into another method.
    Choice 5 It prevents code from executing in a way that follows object-oriented encapsulation.

    Sarwan_Gres wrote:
    Is the instance fields have private accessibility in an immutable class, such as the String class?Usually, but not always.
    "Invoking a method can represent a significant amount of overhead in a program; as such, some compilers will perform an optimization called "method inlining." This optimization will remove a method call by copying the code inside the method into the calling method."The java compiler does not inline methods so this is not relevant to Java. (The JVM does inline methods) The java compiler does inline constants known at compile time but it is a feature causes more trouble than good IMHO.

  • 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.
    }

Maybe you are looking for

  • Error while loading the custom portal transaction

    Hi, After the recent ITS Patches applied, our custom portal transactions are not work fine. Some of the fields are displaced from their position and printing in abrupt position of the screen. Transaction like address change, direct doposit screen...

  • ITunes has encountered a problem and needs to close.  We are

    I've had it with these guys! I recently upgraded to itunes 6, and have had awsome problems ever since. First it stopped my pc from booting up completely, which I had to start in Safe in order to quick restore. Then everything would freeze when I trie

  • Data model in BW 7.0 (NW 2004s)

    Hello friends. The question is about the data model in BW 7.0 in comparison with BW 3.0, 3.1 and 3.5. Is is still the same? I mean, the database tables ofcubes and ODSes, are they still the same, with the same structure, naming convention and so on?

  • Serious Album Art Question!

    here is the situation, for the songs i have purchased it works perfectly, however, for other songs that i have that i have applied album art too, even though when i select it in the iTunes the album art is the same for the whole album, for other albu

  • Query on Multiprovider

    Hi, I build a query on a Multiprovider which contains 3 InfoCubes. In my Query I have only one Key Figure and several characteristics. I know from which InfoCube my Key Figure come from, therefore I add the characteristic Infoprovider to the Filter a