Staticblock of static final variables

I have a class with
Static block
Which has dao call.
So when this class is called for first time static block is called .
Now suppose I return instance of this class from my session bean to a servlet.
Will this servlet also call static block ?

If the class has been created and the static initializer called then it won't be called again.

Similar Messages

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

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

  • Static/Final variable

    When progressing through a series of tests for simple adding/subtracting I find that my variables which I want to remain constant are changing, despite if i set them to static or final. The addition method adds variable 'a' to 'b', the second test adds variable 'a' to 'd'. Instead of adding 'a' to 'd' it is adding 'a+b' to 'd'. How can I set these variables so they are constant each time they are called?
            BigInt a = new BigInt(123456789);
            BigInt b = new BigInt(1234);
            BigInt c = new BigInt(-123456789);
            BigInt d = new BigInt(-1234);
            System.out.println("Case 1:" + a + " + " + b + " = " + a.add(b));
            System.out.println("Case 2:" + a + " + " + d + " = " + a.add(d));

    "static" means that an attribute is a class attribute, shared among all instances.
    "final" means for attributes that its value (either primitive or the reference) cannot be changed - it does not mean that the object it refers to is immutable.
    You can't set them constant - but look how String handles things, it doesn't modify the String itself, but returns a new instance with the desired values. Let add() return a BigInt instead of modifying the instance it's called on.

  • 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

  • Final Variable changed on runtime...

    Hello, I recently did a test with my program, which involved the use of 32 clients connecting to a server from a single application, however on runtime, the some final variables had their values changed, for example
    private static final Point point1 = new Point(100,100);
    had changed values to 480,360, and the default Point in my Point class had changed it's value from 0,0 to another value as well. How is this possible? The only methods used on the finalized point was equals/distance, which both do not affect the private fields of point, yet they were changed after logging in about 29 clients or so.
        public int distance(Point p2)
            return Math.max(Math.abs(p2.x - x), Math.abs(p2.y - y));
        public boolean equals(Point p)
            return (p.x == x && p.y == y);
        public boolean equals(Object obj)
            if (obj instanceof Point)
                return (((Point) obj).x == x && ((Point) obj).y == y);
            return false;
        }And here is where they are used
        private static final Point mine = new Point(167, 105);...
                        if (!cLoc.equals(mine))
                            if (cLoc.distance(mine) <= 18)
                                Player.jump(mine);
                                Player.Mine();
                                lastMineTime = 0;
                        }Any idea why this happened?

    Sorry, I was not clear enough
    Here is my Point class
    http://pastebin.com/m6075a9d8
    Now, after logging on about 38 clients (about 204 threads lol....), the constant fields get changed, for example within the point class, the "DEFAULT" gets changed to a random variable (which never happened before when logging on 10-20 only)
    Same goes for my other constant variables, their values get changed.
    For Example these Points:
        private static final Point sellPoint = new Point(417, 357);
        private static final Point mineExit = new Point(156, 90);
        private static final Point mineExitPoint = new Point(53, 399);
        private static final Point mineEntrance = new Point(45, 397);
        private static final Point mine = new Point(167, 105);Would get changed to something totally different, while the only functions used on those points are equals/distance.
    Here is an image of the Point instance while in debug mode:
    http://img193.imageshack.us/img193/6774/javaerror.jpg
    As you can see , mineExit takes the place of mineExitPoint (however I don't know why..), and mineExitPoint remains the same.....
    Another image:
    http://img6.imageshack.us/img6/9088/javaerror2.jpg
    Edit: Could it be the fact that around 30 threads are checking the same static/final variable at once?
    Edited by: Naki on Jul 1, 2009 6:43 PM

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

  • 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

  • Local final variables

    Hi!
    I suppose this topic pops up from time to time in forums (I've found some threads after google-ing some), but I couldn't find any authentic answers to this.
    According to the standard coding guidelines, how on Earth should you write local final variables?
    The java coding guidelines don't explicitly mention this case, only class-level final (static final) variables and some "ANSI" constants. (I don't have any idea what "ANSI constant" is supposed to mean, anyway).
    Thanks!

    public int getSomeValue(final String parameter) {
    final int length = parameter.getLength();
    // do something
    }Would you call "length" a constant here? Obviously
    not, so why do we declare it final? Because it
    doesn't change during the execution of this method
    and to avoid accidentally assigning a different value
    to it.I'm not sure I wouldn't. For several years I've been pretty satisfied with C++'s notion of "const" (in fact, I really miss real "const" functionality in Java, but that's another story).
    You could write the equivalent in C++:
    int getSomeValue(const std::string parameter) {
    const int length = parameter.length();
      // or .size()? I don't remember, but doesn't matter... :)
    }You could even write things like this:
    for(int i=0;i<5;++i) {
    const int j = 2*i;
    std::cout << j << endl;
    }So, C++ says: if a variable is "const", its value won't change after it's created. The way I see it, the const variable is "recreated" every time you step into the block where it's defined from the outside. (I don't know whether it looks like the same from the implementation point of view, but that doesn't matter.)
    And whatever C++ says, it's so, because it is a correct language. :)
    Anyway, what you're saying makes sense, and if there's a more explicit way of saying "this is a constant" -as you suggested-, I'm going to use it.
    But about the naming convention, I see there's a pretty good unison here, so thanks! :)

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

  • Final variables are also static

    Folks,
    I came a cross statement saying Final variables are also static!
    Is that true? if its true why they are?
    Thanks
    Jl

    If you're initializing the final variable to the same
    value for each instance, then I can see no benefit to
    making it an instance variable. What does the initial value have to do with it?
    By making it static,
    you can 1) save memory 2) make the variable visible
    outside the context of an instance which could be
    useful and 3) make it more clear that the value of the
    variable is not related to any particular instance
    (because it isn't even though it could be declared as
    an instance variable). If the variable is supposed to be static under the design then yes, you get all the things you just mentioned. But whether each instance has the same initial value is pretty much irrevlevant to that.
    Point 2 is arguable because
    maybe you specifically want to require an instance
    before accessing the variable. Also, if you're
    initializing the variable to different values for
    different instances then of course that's a different
    story.Suppose I want to count the number of times methodX has been called on each instance of a class. If I use an instance variable to count the calls, then the initial value would be zero for each instance. It would make little sense to try and use a static variable.

  • Problem with final variables and inner classes (JDK1.1.8)

    When using JDK1.1.8, I came up with following:
    public class Outer
        protected final int i;
        protected Inner inner = null;
        public Outer(int value)
            i = value;
            inner = new Inner();
            inner.foo();
        protected class Inner
            public void foo()
                System.out.println(i);
    }causing this:
    Outer.java:6: Blank final variable 'i' may not have been initialized. It must be assigned a value in an initializer, or in every constructor.
    public Outer(int value)
    ^
    1 error
    With JDK 1.3 this works just fine, as it does with 1.1.8 if
    1) I don't use inner class, or
    2) I assign the value in initializer, or
    3) I leave the keyword final away.
    and none of these is actually an option for me, neither using a newer JDK, if only there is another way to solve this.
    Reasons why I am trying to do this:
    1) I can't use a newer JDK
    2) I want to be able to assign the variables value in constructor
    3) I want to prevent anyone (including myself ;)) from changing the value in other parts of the class (yes, the code above is just to give you the idea, not the whole code)
    4) I must be able to use inner classes
    So, does anyone have a suggestion how to solve this problem of mine? Or can someone say that this is a JDK 1.1.8 feature, and that I just have to live with it? In that case, sticking to solution 3 is probably the best alternative here, at least for me (and hope that no-one will change the variables value). Or is it crappy planning..?

    You cannot use a final field if you do not
    initialize it at the time of declaration. So yes,
    your design is invalid.Sorry if I am being a bit too stubborn or something. :) I am just honestly a bit puzzled, since... If I cannot use a final field in an aforementioned situation, why does following work? (JDK 1.3.1 on Linux)
    public class Outer {
            protected final String str;
            public Outer(String paramStr) {
                    str = paramStr;
                    Inner in = new Inner();
                    in.foo();
            public void foo() {
                    System.out.println("Outer.foo(): " + str);
            public static void main( String args[] ) {
                    String param = new String("This is test.");
                    Outer outer = new Outer(param);
                    outer.foo();
            protected class Inner {
                    public void foo() {
                            System.out.println("Inner.foo(): " + str);
    } producing the following:
    [1:39] % javac Outer.java
    [1:39] % java Outer
    Inner.foo(): This is test.
    Outer.foo(): This is test.
    Is this then an "undocumented feature", working even though it shouldn't work?
    However, I assume you could
    get by with eliminating the final field and simply
    passing the value directly to the Inner class's
    constructor. if not, you'll have to rethink larger
    aspects of your design.I guess this is the way it must be done.
    Jussi

  • HELP: Cannot refer to non-final variable inside inner class

    Below is a function that WAS working beautifully. I had to restructure many things in my code base to suit a major change and I have to make this function static. Since I made this function static, I get some errors which are displayed in comments next to the line of code.
    Can anyone offer any advice how to fix this?
    static private void patchSource( final Target target, final TargetResolver resolver, final TexSheetCommand args ) throws Exception
         boolean bDone = false;
         Element e;
         SAXReader sax          = new SAXReader();
         FileInputStream fis     = new FileInputStream( args.getInputFile() );
         Document document     = sax.read( fis );
         Element root = document.getRootElement();
         if( root.getName().equals( "Sheet" ) )
              XMLParser.iterateElements( root,     new XMLElementCallback()
                                                      public void onElement( Element element )
                                                           XMLParser.iterateAttributes( element,     new XMLAttributeCallback()
                                                                                                   public void onAttribute( Element element, Attribute attribute )
                                                                                                        if( attribute.getName().equals( "guid" ) )
                                                                                                             e = element; // PROBLEM: Cannot refer to a non-final variable e inside an inner class defined in a different method
                                                                                                             // WARNING: Type safety: The expression of type Iterator needs unchecked conversion to conform to Iterator<Attribute>
                                                                                                             for( Iterator<Attribute> it = element.attributeIterator(); it.hasNext(); )
                                                                                                                  Attribute a = (Attribute)it.next();
                                                                                                                  if( a.getName().equals( "randOffset" ) )
                                                                                                                       Integer i = new Integer( resolver.getTotalPermutations() );
                                                                                                                       a.setValue( i.toString() );
                                                                                                                       bDone = true; // PROBLEM: Cannot refer to a non-final variable bDone inside an inner class defined in a different method
              if( ( !bDone ) && ( e != null ) )
                   Integer i = new Integer( resolver.getTotalPermutations() );
                   e.addAttribute( "randOffset", i.toString() );                                                                                                                                            
         FileOutputStream fileOut     = new FileOutputStream( args.getInputFile() );          
         OutputFormat format               = OutputFormat.createPrettyPrint();          
            XMLWriter xmlWriter               = new XMLWriter( fileOut, format );
            xmlWriter.write( document );
            fileOut.close();
    }PS.) on a side note there is a warning on one of the lines too. Can anyone offer help on that one too?!
    Thanks in advance.

    It is already set to that - it does look correct in Eclipse, honest.
    It's just the block that's gone crazy with the formatting. I've spent around 10 minutes trying to tweak it just so it displays correctly but it wasn't making sense.
    I'd rather not turn this conversation into a judgement of my code-style - I already understand that it doesn't conform to the 'Java way' and I've had Java programmers bash me about it for a long time.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Static class variable doesn't store ?

    Hi,
    I'm a beginner in java.
    I defined a static class variable (nodes) in th following code :
    public class MySOMapp extends javax.swing.JFrame {
         private static final long serialVersionUID = 1L;
         private static SOMTrainer trainer;
         private static SOMLattice lattice;
         private static SOMNode nodes;
         private static Hashtable nwordf; 
         public MySOMapp(String args[]) {
              SOMNode nodes = new SOMNode();          //.....But a method of this class, nodes comes null. methos definition :
    private void makesame() {I don't understand why the nodes is null in makesame method which is in the same class with nodes ?
    thanks,
    Yigit

A: static class variable doesn't store ?

thankyou. I solved the problem. But why static fields
are not good idea ? How can i get rid of these...Remove the static word :) Seriously, try to develop a technique to get swiftly out of the static main method. Like this:
class MyClass {
    MyClass() {
        // Your code here instead of in main method.
    public static void main(String[] args) {
        new MyClass();
}

thankyou. I solved the problem. But why static fields
are not good idea ? How can i get rid of these...Remove the static word :) Seriously, try to develop a technique to get swiftly out of the static main method. Like this:
class MyClass {
    MyClass() {
        // Your code here instead of in main method.
    public static void main(String[] args) {
        new MyClass();
}

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

  • Maybe you are looking for