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.

Similar Messages

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

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

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

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

  • Declaring public static final variables in jsp?

    The question is in the title...
    I know this is not a jsp forum, but some people here might know if it's possible or not.
    If yes, how to declare them and how to access them from other jsp pages?
    Thx

    If you need that, you definitely do too much work in your JSPs. You should do all your work in Servlets (or Actions if you're using Struts or something similar).
    Your JSPs should only do the presentation.
    Remember that JSPs are not classes (they are compiled into classes internally, but you don't have direct access to those).
    If you absolutely need such a public static final field that you want to access from several JSPs, just define it in a Class and reference that class from your JSPs.

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

  • The serializable class SpacePainter does not declare a static final serial

    The serializable class SpacePainter does not declare a static final serialVersionUID field of type longWhat does this mean??? It appears as a warning in Eclipse but I have no idea what it is. It happens when I create a class the extends JFrame or JCompnent or JApplet. I finnally got it to stop with this:
    static final long serialVersionUID = 1;

    Because your eclipse is configured that way. You can probably filter the warning. You don't have to implement the serialVersionUID, but you should if you really serialize the exceptions.

  • Serializable class doesn�t declare static final serialVersion of type long

    The serializable class SomeClassName does not declare a static final serialVersionUID field of type long
    I have a lot of these warnings in my current application.
    What does it really mean?
    In what situations do I actually want/need to use this?
    If I need it somehwere, do I just declare this field?

    Putting a version number on a serializable class is a precaution against the class definition changing in a way that confuses ObjectStreams when reading old serialisations.
    You can just declare the varialble, initially make it 1 and crank it up in your source when you change the fields of the class.

  • Static final in (Class or Interface)

    Hello Friends ,
    What is the difference in having a public static final variable in an class and having the same kind of
    declarations in an Interface ?
    Does the interface is better or having it in a class ?
    Thanks in Advance,
    -S

    shyamnambiar wrote:
    But I'm not clear . you mean to say its all the same .It does not make any difference ?The only difference that it makes (and that might be an important difference) is what you communicate with your design an intention.
    Constants should usually be placed within their context since that's where they are going to be used, and that's where developers will look. It's more common to place the constants in the class that they are related to. They should not be placed in an empty final class just because you want to group constants. You should also avoid placing constants in an interface just because you then can implement that interface to "get hold of" the constants.
    Kaj

  • 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

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

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

  • Declaring method arguments as 'final'.

    Hi all
    Is it a good practice to declare method arguments as 'final' in java. Also please let me know how the performance would be effected.
    Ex: private int xMethod(final int i){}
    Thanks in advance.

    You are likely to find performance to be comparable whether you declare your argument as final or not.
    All it means is you cannot change the reference for an object argument or the value of a primitive argument in the method for which it is an argument.
    Note that you can still change the state of an object argument declared final! Final is not the same as const, which Java does not support.

Maybe you are looking for

  • I can't get my ipad apple protection on

    I got an ipad2 for Christmas as well as the applecare and I can't seem to get it on to my ipad I have phone gone into the shop and I can't seem to find out why it is not going on just wondered if anyone else has had this problem

  • How to unlock my iphone 5

    forget my passcode how to unlock my phone

  • Static NAT with port translation

    Hello All, I have a server running web application on 443 and now I want to publish it on Internet with static nat and just for port 443,  I am thinking that following configuration should be fine, can anyone comment on it.   10.1.1.2:443         10.

  • Can't get 10.2 to work

    I have recently installed Flash Player 10.2 on Windows 7 64 bit.  Flash Player no longer works. Everytime I visit a page that requires it I am asked to download it.  If I do so I am asked to reboot.  After this I am back to square 1 - FP does not wor

  • Very Loud Fan -- How to make it stop?

    I have a new MacBook Pro that I purchased in November, replaced in December. Recently, the fan has been running really loudly all the time. In one of the other posts, someone spoke about smsFanControl, that I downloaded. The fan monitor tells me that