Imposing constraints - final & (const?)

Hi
i'm looking to impose a unique identifier on a class (for an inventory system) and according to a previous exam question there are two ways of applying such a constraint.
I had thought it was final or const but on further research i understand that const is reserved but not used. I'm confident that final is one of the ways..
Any ideas? Greatly appreciated

Hi
i'm looking to impose a unique identifier on a class
(for an inventory system) and according to a previous
exam question there are two ways of applying such a
constraint.
Can you please expand upon what it is that you are looking for? For example do you really mean class or do you mean instance? And what do you mean by "impose"?

Similar Messages

  • Flat File vs using final constants - which is better appraoch

    Hi
    i have a requirement where i have set some states variable.
    it goes like this:
    state A , some indicator A ,indicator B ,flag A : final state set to be set
    1 , true , A , 0 : Declined
    1 , false , B ,0 : PreDeclined...
    ...... like this i have some 20+ rows.. below 50
    since these are states .. this may increase.. but not frequently
    i would like to know which is best way to implement the above logic. My peer suggested to capture all that data as constants /hard code. I was thinking to store them in CSV and then read. but my peer was mentioning using I/O operations slows performance. can u please suggest me a better way ( not DB since its requires lots of permission etc..)

    thats interesting. can u please let me know how to use enums to fit my above requrement.
    i have used enums eariler where my requirement is just return descriptionstring to code. . ie.. is just only one constant.more over those enums are generated .. and they do correspond to a db table.
    but here what i want is a basically look up based upon 3 elements. and return 4 the element..
    i'm not sure on how to use enums for that.

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

  • Interfaces and final variables

    So I understand that I am not supposed to put my final variables or constants into an interface, but then where?
    I have 2 classes that implement an interface, and they both allow listerners to be added to them, through that interface. They both fire property events on the listener with the same property. Currently I just put the property id constants into one class and reference it from the other. But it appears to me the best place for the definition of these common properties is in the interface!?

    So If you read over all the postings, you'll know exactly why they say, never to create classes for the purpose of grouping constants, it is confusing.
    More explicitly, it is lazy. The reason you are grouping the constants has nothing to do with the relationship between the constants and their use within the program, you are grouping them because you are tired of typing a long declaration everytime you want to use them within the program. So, the overall design of your program is being warped by design decisions that are based on laziness.
    The reason people put them in interfaces, "public interface Globals...", is so that importing that namespace through inheritance doesn't suck up that "valuable" superclass (which I will have to remember to rant about on some other thread). It is probably the case that the most efficient way to do this is to use static getters: getPI(), getOrigin(), getNewYears(), whatever. You will see an awful lot of constants that have been replaced over the years with getters. As the code matures, it isn't peculiar to see the flexibility of the programme being reduced or impeded by the constraints and constants implicit in the codesbase.
    Andrew

  • Declaring variables or constants at the start of a class

    Hi, I have a question. I am in an introductory java course and my instructor says that anything that is declared outside of a method (ie. very beginning of a class) must be a final constant.
    She says that I must use
    public static final int EXAMPLE_CONSTANT;
    and that it can not be changed (I know this, it is declared as a constant)
    What I do not understand, is she says that I could not do say
    int ExampleVariable;
    in any way outside of a method because the methods would not be able to access it.
    Is this true? I have made programs before with declarations like that just at the beginning of a class, and they have worked fine and I have been able to change the variable and access it inside my methods. Why does she say that will not work and that it can only be a constant? Can someone explain to me, is it maybe bad practice?

    I will make an example of what we are doing and and what she says I can not do.
    This is what we start with:public class OddCount{
         public static final int MAX_ODD=21;
         public static void main(String[] args){
              outputOdds();
              MAX_ODD=11; // I realize this does not work
              outputOdds();
         public static void outputOdds(){
              for(int i=1;i<=MAX_ODD;i+=2){
                   System.out.print(i+" ");
    }Obviously we can not assign the value of 11 to MAX_ODD because it is a constant and already initialized. This is what she wanted us to realize. That's all fine and I understand that.
    My question is obviously "Why don't we just make a variable instead of a constant and use that in the same place? Replace 'public static final int' with just 'public static int'. "
    Her answer is that it is not possible because we would not be able to use the variable within the method, she said because it would be "outside of the scope of the variable."
    She has me very confused haha, mainly because I tried what I proposed and it works but she says it will not.

  • Managing constants in large applications

    This is an issue that has come up many times in my projects. While I try to avoid the practice, I almost always have some sort of Constants.java class that contains a bunch of public static final constants. This includes things like application name, filenames for configuration files, version numbers, network ports, etc. Sometimes I'll split them up into multiple classes (e.g., AppConstants.java and NetworkConstants.java).
    Is this an accepted practice in larger applications, or are global constants typically handled differently? I've always considered my solution to be inelegant, but I haven't come up with a better way of doing it. Suggestions?

    > Yes, I do typically use an interface to hold my
    constants. I know I said "class" above.
    This is considered a bad practice, or "antipattern", to wit:
    Effective Java - Joshua Bloch, Chapter 4, Item #17: Use interfaces only to define types.
    The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface.
    In summary, interfaces should only be used to define types. They should not be used to export constants.
    ~

  • Constants for JAX-RPC

    Hello!
    How can I define constants in a value object? I need constants that should
    be used in a value object both by server and client. From Java language
    perspective, I can define static final constants in either value object
    itself or in separate class/interface. When servicegen and clientgen tasks
    create WSDL and remote stubs for value objects, they strip out my constants
    definitions.
    For now I use separate Constants class that I put manually into client JAR
    file. It works, but to make it cleaner I would like to define these
    constants in WSDL file. How can I do it?
    Thanks in advance!
    Michael Jouravlev.

    JAX-RPC does not say how to handle public final fileds in
    value types.
    One way to solve this problem may be to specify fixed attribute
    in the xsd:attribute.
    eg:
    <xsd:attribute name="country" type="xsd:string" fixed="US"/>
    But this will work only for simpleTypes. Anyway, I will file a feature
    request for this (CR080597). Hope someone(jax-rpc/soap builders)
    will comeup with a better solution.
    regards,
    -manoj
    "Michael Jouravlev" <[email protected]> wrote in message
    news:[email protected]..
    Hello!
    How can I define constants in a value object? I need constants that should
    be used in a value object both by server and client. From Java language
    perspective, I can define static final constants in either value object
    itself or in separate class/interface. When servicegen and clientgen tasks
    create WSDL and remote stubs for value objects, they strip out myconstants
    definitions.
    For now I use separate Constants class that I put manually into client JAR
    file. It works, but to make it cleaner I would like to define these
    constants in WSDL file. How can I do it?
    Thanks in advance!
    Michael Jouravlev.

  • How to use constant in expression language

    I have class Constant which contains
    public static final (constant fields).
    I want to use those constants in expression language in jsp
    ${requestScope.result eq with some constant}
    <c:if test="${requestScope.result eq '<%= Constants.MODE %>'}">
                   Hello World
              </c:if>     
    It does not print Hello World
    even though MODE is 'hello' and result is also set to 'hello'.
    Message was edited by:
    mihir_kapadia

    Its not that simple. There is an article in [url http://www.javaranch.com/journal/200601/Journal200601.jsp#a3]javaranch  about the usage of constants in EL.
    There is [url http://forum.java.sun.com/thread.jspa?forumID=45&threadID=508847]this  cool code snippet from forum user evnafets that would help you with your problem.
    ram.

  • "private final" vs. private

    hi,
    I'm sure that this question has been dealt with before in here, but I was unable to find anything via the search.
    Basically, is there a point to making a method both private and final instead of just private?
    What about with a member of a class?
    final is supposed to in-line the code.
    Does private on its own do this too?
    I'd be interested in people's knowledge on this matter.
    thanks,
    Alan

    final variables means that you can only assign them once ...
    If you add static, then the variable is shared between the objects...Unfortunatly I think this is not completely right. I do not know why, but when you define a static final constant it's value is somehow obtained at compile time, not sharing it. If later you modify the constant value, the old classes using it should be recompiled, or they will still get the old value, while new classes will get the new value.
    This, to my understanding, means that the constant is not being shared among classes.
    Although a constant should remain invariable in time, have you never had the need to change a constant defined in an interface?

  • Static and final modiers

    Brief summary: I want to make the JButtons, JLabels, and JPanels public static final. Is that bad, and why? And what the heck is the Java system doing when it compiles and runs a program that does this? Is the code more efficient?
    More questions below.....
    I'm new to making GUI designs with Java. I am going to school and my teacher is making us do GUI interfaces in JAVA.
    Early on, I learned that constants are identifiers similar to variables except that they holda particular value for the duration of their existence. QUESTION ONE: what happens during run-time, how does JAVA handle this constant?
    I also learned that some methods may be invariant, as with a simple extension. These methods should be marked final. The subclass inherits both a madatory interface and a mandatory implementation. So I guess you use a final method when you want to model to a stric subtype relatinoship between two classes. All methods not marked final are fair game for re-implementation.
    Well, that's good and well. So then I started thinking about static. That's a keyword in Java and when used with a variable, it's shared among all instances of a class. There is only one copy of a static variable for all objects of a class. So then again, I noticed that the programs in my book that used final usually threw in the word static before it. Memory space for a static variable is established when the class that contains it is referenced for the first time in a program.
    Well, that too is great? Question 2: In my GUI programs, can I declare all the buttons (JButtons), labels (JLabels), panels (JPanels) as being final constant static?
    In the program I don't intend to change the type of button, or JPanel so why not make it a constant? As long as I'm doing it, why not make it static? WHAT IS ACTUALLY GOING ON THEN IN MY PROGRAM WHEN I DO THIS?
    Question 3: What goes on in JAVA when I make a method or function public static final. Is that what the Math class does? How is that handled during run-time? Is the code faster? Is it more efficient?
    Question 4: If I make a class final, that means a subclass cannot extend it? Or does it mean that a subclasss cannot change it? I know that if the function or method in the parent class was final, then the subclass inherits both a madatory interface and a mandatory implementation....So if the class is final, then what?

    Final makes a variable a constant. You can not change the variable once it has been initialized. A final method cannot be overridden in subclasses. So I would not make any button or menu item final unless you never want to change it. Final should be used to protect data. I don't believe there is a performance difference if they are used.
    Static variables exsist only once. So if you have a class with a static variable and create several instances of that class the static variable will be the same in all of them.
    Again data protection. Static variables are useful but a pain to use. I don't think there is a performance advantage with using them.

  • Static and final keyword questions

    Brief summary: I want to make the JButtons, JLabels, and JPanels public static final. Is that bad, and why? And what the heck is the Java system doing when it compiles and runs a program that does this? Is the code more efficient?
    More questions below.....
    I'm new to making GUI designs with Java. I am going to school and my teacher is making us do GUI interfaces in JAVA.
    Early on, I learned that constants are identifiers similar to variables except that they holda particular value for the duration of their existence. QUESTION ONE: what happens during run-time, how does JAVA handle this constant?
    I also learned that some methods may be invariant, as with a simple extension. These methods should be marked final. The subclass inherits both a madatory interface and a mandatory implementation. So I guess you use a final method when you want to model to a stric subtype relatinoship between two classes. All methods not marked final are fair game for re-implementation.
    Well, that's good and well. So then I started thinking about static. That's a keyword in Java and when used with a variable, it's shared among all instances of a class. There is only one copy of a static variable for all objects of a class. So then again, I noticed that the programs in my book that used final usually threw in the word static before it. Memory space for a static variable is established when the class that contains it is referenced for the first time in a program.
    Well, that too is great? Question 2: In my GUI programs, can I declare all the buttons (JButtons), labels (JLabels), panels (JPanels) as being final constant static?
    In the program I don't intend to change the type of button, or JPanel so why not make it a constant? As long as I'm doing it, why not make it static? WHAT IS ACTUALLY GOING ON THEN IN MY PROGRAM WHEN I DO THIS?
    Question 3: What goes on in JAVA when I make a method or function public static final. Is that what the Math class does? How is that handled during run-time? Is the code faster? Is it more efficient?
    Question 4: If I make a class final, that means a subclass cannot extend it? Or does it mean that a subclasss cannot change it? I know that if the function or method in the parent class was final, then the subclass inherits both a madatory interface and a mandatory implementation....So if the class is final, then what?

    You have a lot of questions..
    You make a method final if it should not be allowed for subclasses to override it.
    If you make a class final, you will not be able to subclass that class.
    A static method is a class method, i.e. you don't need to create an instance of the class to call the method.
    You can make any object and primitive final, but for objects, you are still able to modify what is inside the object (if there is anything you can and are allowed to modify), you just can't change the final reference to point to another object.
    When you make a variable final, you sometimes make them static as well if they should work like constants. Because there is no reason that every instance of the class has their own copy of constants.
    If you make everything static, why even bother to work with object-oriented programming. It gives you no reason to make instances of your classes. You should try not to make static variables and methods when there is no need for it. Just because you start from a static main method, it doesn't mean it is necessary to make all variables and methods static.
    Don't think so much about performance issues as long as you are still learning java. When you make a method final, it is possible for a compiler to inline that method from where you call the method, but you will hardly gain much in performance with that. In most cases it's better to optimize the code you have created yourself, e.g. look at the code you run inside loops and see if you can optimize that.

  • Related with Final Keyword...

    Hi,
    I written the following code to iterate over an array :
    for(final int i:arr)
    System.out.println(i);
    }

    jschell wrote:
    I really doubt that the compiler doesn't erase the final part.
    It is a compile time rather than run time check.Runtime as well, it seems.
    public class Final {
      public static final int i = 999;
    public class FinalChanger {
      public static void main(String[] args) {
        Final.i = 123;
        System.out.println(Final.i);
    }1) Compile both without the final keyword in Final.java
    2) Put final into Final.java, and recompile.
    3) Run javac -cp . FinalChanger
    Exception in thread "main" java.lang.IllegalAccessError
            at FinalChanger.main(FinalChanger.java:3)
    :; javap -s -c -verbose -classpath . Final
    Compiled from "Final.java"
    public class Final extends java.lang.Object
      SourceFile: "Final.java"
      minor version: 0
      major version: 50
      Constant pool:
    const #1 = Method       #3.#14; //  java/lang/Object."<init>":()V
    const #2 = class        #15;    //  Final
    const #3 = class        #16;    //  java/lang/Object
    const #4 = Asciz        i;
    const #5 = Asciz        I;
    const #6 = Asciz        ConstantValue;
    const #7 = int  999;
    const #8 = Asciz        <init>;
    const #9 = Asciz        ()V;
    const #10 = Asciz       Code;
    const #11 = Asciz       LineNumberTable;
    const #12 = Asciz       SourceFile;
    const #13 = Asciz       Final.java;
    const #14 = NameAndType #8:#9;//  "<init>":()V
    const #15 = Asciz       Final;
    const #16 = Asciz       java/lang/Object;
    public static final int i;
      Signature: I
      Constant value: int 999
    public Final();
      Signature: ()V
      Code:
       Stack=1, Locals=1, Args_size=1
       0:   aload_0
       1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
       4:   return
      LineNumberTable:
       line 1: 0
    :; javac -version
    javac 1.6.0_06
    :; java -version
    java version "1.6.0_06"
    Java(TM) SE Runtime Environment (build 1.6.0_06-b02)
    Java HotSpot(TM) Client VM (build 10.0-b22, mixed mode)

  • How do i create a database template from the command line?

    Hi,
    As part of implementing a backup and recovery strategy for a client (including disaster recovery) I want to automate the creation of a database template From an Existing Database (Structure as well as data) via a script that will run every night.
    The background to this is that we will also be using RMAN to take backups of the database concerned but the client does not want to wait while an RMAN backup is restored and so wants an additional level of insurance in the form of a ‘standby’ clone database.
    The idea is that nightly we will run a script that creates a database template from the Existing Database (Structure as well as data) and then transfers the 2 files involved e.g. DB_data_included.dbc and DB_data_included.DFB across to a standby server where they can be used to recreate the database in the event of us needing to after e.g. a complete server failure.
    So I have a couple of questions about this that I would be very grateful if something could answer for me:
    1)     Is it possible? That is, can a database template be created from some utility by supplying a series of parameter=value pairs on the command line?
    2)     If yes how do I go about it, what utility do I use (the emca utility?). and what parameters do I need to supply on the command line to create the template?
    3)     The intention is that the script to create the template will run in the early hours of the morning when no-one is using the database but what state does the database need to be in when the template creation script runs i.e. up, down, mounted and does the creation of a template affect the state of an already up database i.e. if I kick off the template creation script and the database is up will it switch it into mount mode or anything like that? My concern here is that I want to make sure I understand exactly what is going on so that no users or connected external systems are affected?
    Thanks in anticipation of someone being able to guide me on what to do or what documentation to read.
    Also if you require any clarification on what i'm asking please post up your query and i'll respond ASAP.
    Kind Regards,
    George Johnston
    OCP 9i DBA

    Sybrandb,
    Firstly thanks for you reponse.
    However, I don’t agree that dbca only creates empty databases otherwise why does the option to create a template from an existing database (structure as well as data) exist in the dbca wizard?
    I have performed a test case where I have a created a database template including data on one 10g server. I have then used the files generated to recreate that database on a separate server. When the new database is started it is an exact copy of the original. So it’s not empty at all , it’s exactly what the client wants.
    So I don’t agree that I’m gaining zero.
    Why is this approach doomed to fail?
    There a number of reasons why I “just set up a proper standby database”
    1.     Time – I’m on a customer site in a tight engagement where the customer wants maximum value for money. I don’t have standby database skills and the customer isn’t willing to pay for me to learn on the job so please understand the tight circumstances I’m working in.
    2.     Availability – As far as I know the client is running 10.2.0.3.0 standard edition. Correct me if I’m wrong but is standby db available in that edition. Where do I look to check V$OPTION.
    On the RMAN duplicating a database front it’s an area I haven’t used before but I will take a look at it.
    Also please revisit the context of my original posting where I state
    The background to this is that we will also be using RMAN to take backups of the database concerned but the client does not want to wait while an RMAN backup is restored and so wants an additional level of insurance in the form of a ‘standby’ clone database.
    So please understand that this a quick fix that the client wants developed in the minimum time possible in ADDITION to a full nightly RMAN backup being taken.
    In an ideal world I’d have the time to follow best practice but in the real world of on-site customer support I just need to get the job done operating under the customer imposed constraints.
    Many Thanks,
    George Johnston
    OCP 9i DBA

  • Clustering of Oracle AS 10.1.3.0 nodes in active-active topology

    Hi,
    The following requirements for clustering in our environment exist:
    * Active-active topology
    * External hardware load-balancer
    * Fail-over
    * Application session-state replication
    We use multiple Oracle AS 10.1.3.0 nodes. Applications are deployed on 2 or more OC4J instances on those nodes.
    I've read the Oracle docs on clustering and I have some questions regarding the clustering configuration to use:
    1. When an external hardware load-balancer is used, is configuring an Oracle AS cluster needed then? The docs talk about clusters, but in some cases I'm not sure whether an Oracle AS cluster or a hardware cluster is meant.
    2. It seems not entirely clear what type of application clustering to use in combination with an Oracle AS cluster: either multicast or peer-to-peer? If I'm correct the Oracle docs suggest to use dynamic peer-to-peer application clustering if an Oracle AS cluster is used and multicast for standalone OC4J. Is that correct?
    Thanks,
    Ronald

    1. Well, the idea is to have all clients route their HTTP requests to the physical load-balancer. The load-balancer will route/forward the requests to one of the Oracle AS nodes based on the load on those machines. If application state is synchronized between the application(s) on the OC4J instances, it would not be necessary to configure an Oracle AS cluster? Or are there advantages for having such a cluster? One of the pros I can think of would be that groups are automatically created so deployment/management of the application(s) becomes easier. Are there any other? Or is this configuration w/o Oracle AS cluster not a good idea?
    2. Clear.
    3. JMS, thanks for the tip.
    4. Yes we use Oracle RAC. Does that impose constraints on the Oracle AS clustering and/or application clustering?
    Ronald

  • Best practice for declaring and initializing String?

    What is the best practice for the way Strings are declared in a class?
    Should it be
    private String strHello = "";
    or should I have the initialization in the constructors?

    The servlet constructor is usually called once, when the servlet is first accessed. But then again maybe something else happens, google servlet life cycle if you must know.
    But let's take a step backwards here. It seems like you are trying to put fields into servlets. Don't do that. When two users fetch the servlet's URL at the same time, the fields are shared between the two hits. If you store something like HTTP parameters in the fields, the two hits' parameters will get mangled. The hits can end up seeing each other's parameter values.
    The best way is not to have fields in servlets. (Except maybe "static final" constants, sometimes rarely something else.) Many concurrency worries go away, servlet life cycle worries go away, servlet constructors go away, init() usually goes away.

Maybe you are looking for