Results 1 to 17 of 17
  1. #1
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    7

    Default What are statics?

    I have some time to kill and I'm curious as to how statics work. I remember in one of the quiz questions there was something like
    Java Code:
    class mainClass{
           public method1(){
           }
    }
    
    static someStaticClass(){
           //this method gets called at compile time first?
    }
    Maybe I'm not google-ing the correct term but whenever I search for static methods in java(or similar) I just get things like a static subroutine cannot use the this operator while non static subroutines can create new instances of the class. I already knew about that and was more looking towards the example of statics being called at compile time.

  2. #2
    fishtoprecords's Avatar
    fishtoprecords is offline Senior Member
    Join Date
    Jun 2008
    Posts
    571
    Rep Power
    7

    Default

    A static function is one that you can call globally, without an instance. There are also static classes, but you should not use them.

    Consider a Student class. You can do things like:

    Java Code:
    Student oneOfThem = new Student();
    oneOfThem.assignGrade("c");
    The "assignGrade" is an instance function, you apply it to an instance of Student.

    Now consider
    Java Code:
    Calendar rightNow = Calendar.getInstance();
    You are calling the "getInstance" function without having an instance.
    So the getInstance function is declared "static"

  3. #3
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    7

    Default

    Sorry I wasn't clear enough. I meant static initializers(just didn't know what they were called)

    I get that their used for defining variables at compile time instead of run time and that they get called before any other method. There has to be something more to it though, isn't there? Whats wrong with declaring your variables inside the class or right when you need to use them? Why go through the extra hassle of figuring out every variable needed and then creating an initializer for them?

  4. #4
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Talking static

    Quote Originally Posted by xcallmejudasx View Post
    Sorry I wasn't clear enough. I meant static initializers(just didn't know what they were called)
    Java Code:
    class Clyde{ String name; static{ name = new String( "Clops" );} }
    Now Clyde Clops. ( ...?... I thought it was funny(!))
    Quote Originally Posted by xcallmejudasx View Post
    I get that their used for defining variables at compile time instead of run time and that they get called before any other method. There has to be something more to it though, isn't there? Whats wrong with declaring your variables inside the class or right when you need to use them? Why go through the extra hassle of figuring out every variable needed and then creating an initializer for them?
    Instance counters.
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

  5. #5
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    7

    Default

    Ok, so lets add a counter in the Clyde class. An instance counter would keep track of each type Clyde was used? So static initializers could be used as a form of security making sure only a set amount of that object are created or help with memory by clearing the cache or something after a certain number of initializes?

  6. #6
    sai
    sai is offline Member
    Join Date
    Nov 2008
    Posts
    14
    Rep Power
    0

    Default

    According to my knowledge the method or variable which is declared static is shared among all the objects.If any changes done by one object to the static variable or method will get effected to all the objects.
    If i said anything worng please let me know.

  7. #7
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,371
    Blog Entries
    1
    Rep Power
    20

    Default

    Quote Originally Posted by sai View Post
    According to my knowledge the method or variable which is declared static is shared among all the objects.If any changes done by one object to the static variable or method will get effected to all the objects.
    If i said anything worng please let me know.
    Yes you are correct lol. If you really want to see and proof here, why don't you post a simple code segment here to see. :)

  8. #8
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    7

    Default

    Quote Originally Posted by sai View Post
    According to my knowledge the method or variable which is declared static is shared among all the objects.If any changes done by one object to the static variable or method will get effected to all the objects.
    If i said anything worng please let me know.
    Ok that's actually really useful information. So instead of having to set say each objects ownerID upon creation I can have a static initializer that sets it in the beginning and it won't need to be defined each time.

    Thanks a lot guys for the information. I'm pretty sure I get how and when to use them now.

  9. #9
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    7

    Default

    I was reading about Enums and this line jumped out at me "You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time" (taken from Enum Types (The Java™ Tutorials > Learning the Java Language > Classes and Objects))

    Would having an enum accomplish the same thing as having a static initialiazer?

    The example they use is
    Java Code:
    public enum Planet {
        MERCURY (3.303e+23, 2.4397e6),
        VENUS   (4.869e+24, 6.0518e6),
        EARTH   (5.976e+24, 6.37814e6),
        MARS    (6.421e+23, 3.3972e6),
        JUPITER (1.9e+27,   7.1492e7),
        SATURN  (5.688e+26, 6.0268e7),
        URANUS  (8.686e+25, 2.5559e7),
        NEPTUNE (1.024e+26, 2.4746e7);
    
        private final double mass;   // in kilograms
        private final double radius; // in meters
        Planet(double mass, double radius) {
            this.mass = mass;
            this.radius = radius;
        }
        private double mass()   { return mass; }
        private double radius() { return radius; }
    
        // universal gravitational constant  (m3 kg-1 s-2)
        public static final double G = 6.67300E-11;
    
        double surfaceGravity() {
            return G * mass / (radius * radius);
        }
        double surfaceWeight(double otherMass) {
            return otherMass * surfaceGravity();
        }
        public static void main(String[] args) {
            double earthWeight = Double.parseDouble(args[0]);
            double mass = earthWeight/EARTH.surfaceGravity();
            for (Planet p : Planet.values())
               System.out.printf("Your weight on %s is %f%n",
                                 p, p.surfaceWeight(mass));
        }
    }
    Would it be more/less/null effective to do something along the lines of

    Java Code:
    				public enum Planet {
    				    Planet(double mass, double radius) {
    				        this.mass = mass;
    				        this.radius = radius;
    				    }
    				    private double mass()   { return mass; }
    				    private double radius() { return radius; }
    
    				    double surfaceGravity() {
    				        return G * mass / (radius * radius);
    				    }
    				    double surfaceWeight(double otherMass) {
    				        return otherMass * surfaceGravity();
    				    }
    				    public static void main(String[] args) {
    				        double earthWeight = Double.parseDouble(args[0]);
    				        double mass = earthWeight/EARTH.surfaceGravity();
    				        for (Planet p : Planet.values())
    				           System.out.printf("Your weight on %s is %f%n",
    				                             p, p.surfaceWeight(mass));
    				    }
    				}
    
    				static{
    					MERCURY (3.303e+23, 2.4397e6),
    				    VENUS   (4.869e+24, 6.0518e6),
    				    EARTH   (5.976e+24, 6.37814e6),
    				    MARS    (6.421e+23, 3.3972e6),
    				    JUPITER (1.9e+27,   7.1492e7),
    				    SATURN  (5.688e+26, 6.0268e7),
    				    URANUS  (8.686e+25, 2.5559e7),
    				    NEPTUNE (1.024e+26, 2.4746e7);
    					final double G = 6.67300E-11;
    					private final double mass;   // in kilograms
    				    private final double radius; // in meters
    				}

  10. #10
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Talking instance counter

    Not necessarily null or ineffective, but putting a this pointer in an enum - let's say for the moment that we would normally see that in beginner. To say the least, it either should not work or bring howls of laughter from Copernican heliocentrism - Think of an enum as something like a static final that maps strings to a numeric value, with 1,2,3,4,5... and so on being the defaults. I abandoned enums early due to their placment in the compiled work being used in another api in a manner that reeked of intrusion portal. In fact the behaviour of the entire system switched on what was put in the enum .... some appealing avenues of study are available, dig through H2 to find a rather nifty issue that is a candidate for study on one of those nights when you cannot sleep and are not really focused and want to spend a minimum of four or five hours on unguided exploratory study.

    The one thing I have thought of for the moment that makes sense is the potential for a workaround for the compiler error that results from trying to init a static final in the constructor. If it would work, we could do static final current system time static{ time = System currentTimeMillis();} then do epoch's in the constructor. An instance counter is done like this:
    Java Code:
    /*
     * I waste too much time trying to write comments other people can understand.
     * Correct source code is self documenting. Inverse logic.
     */
    public class LogonShell
    {
        long FinshTime;
        float TotalTime;
        String userName;//
        String suppliedName;
        StringBuffer sb;//
        private boolean defaultIdentity;
        Integer HASHCODE;long StartTime;
        public volatile boolean isValid;
        private transient boolean commonName;
        public volatile boolean shortLogonName;
        CommonPasswords cOMMONpASSWORDS = new CommonPasswords();//
        static String newline = System.getProperty("line.separator");
        private transient int defaultUserHashCode = -1085510111;// "Default".hashCode()
    
        //
        int[] digraphs = {-8,9,-15,18,-8,-14,10,-6,3,-1,14,-7,6};// tech override, app enters controlled state
    
        // Shoud be replaced with pool ntp server
        static long seedTimeLong;//
        static{seedTimeLong = java.lang.System.currentTimeMillis();}
        //
        java.security.SecureRandom random;
    
        // Hey, let's add a TreeMap - the're always handy.
        java.util.TreeMap tm = new java.util.TreeMap();
        // .........
    variant spellings of variable names, if any, are an adjunct to efficient time disposition while coding and are not intended to invite critical review.

    To replace
    Java Code:
    static{seedTimeLong = java.lang.System.currentTimeMillis();}
    with ++seedTimeLong resuts in what amounts to an instance counter. We could then do Interger whichOneIsThis = new Integer(seedTimeLong);// in the constructor resulting in an efficient implementation of what amounts to each whatchamacallit knowing which whatchamacallit it is, .... sort of an identity. Which raises an interesting design issue: What if we could make static initializer blocks synchronized?... wow, that would be handy!

    { message edit: see: recompile in advanced }

    What's the latest on GRB 080319B ...?
    Last edited by Nicholas Jordan; 11-23-2008 at 03:04 AM. Reason: additional information
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

  11. #11
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    7

    Default

    Just from the little I've read about synchronization and static initializers I'm under the impression that this wouldn't be possible unless you were running multiple threads synchronized with each other. I'm understanding that SI's are implemented in a stack order(first in first out) sorta fashion and having anything else would be against the whole concept, correct? Each thread/initializer would be unaware of the other ones but all running at the same time accomplishing multiple tasks as if it was one big initializer?

    Am I correct in thinking this or has your post Nicholas, once again, confused the hell out of me and I completely missed the boat on what you were talking about.

  12. #12
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Thumbs up excellent work.

    Quote Originally Posted by xcallmejudasx View Post
    Am I correct in thinking this or has your post Nicholas, once again, confused the hell out of me and I completely missed the boat on what you were talking about.
    Actually, this is excellent work, you moved ahead of me - and in total understanding of what my post was all about.
    Quote Originally Posted by xcallmejudasx View Post
    Just from the little I've read about synchronization and static initializers I'm under the impression that this wouldn't be possible unless you were running multiple threads synchronized with each other. I'm understanding that SI's are implemented in a stack order(first in first out) sorta fashion and having anything else would be against the whole concept, correct? Each thread/initializer would be unaware of the other ones but all running at the same time accomplishing multiple tasks as if it was one big initializer?
    SI == Static Initializers == static{} Correct? IOW I have not seen the abbreviation SI

    What you are thinking here would seem to be conceptually correct. The issue that clouds the matter is that an implementation of a jvm is at the mercy of compiler science and the person who wrote the jvm. The Java Virtual Machine is a specification, a description of a machine. With all the compiler switches and freedom left to the compiler writer, I would think that the words that I have heard that the classes are loaded ( in order ? ) and static init blocks are run before the constructor is run ~ so it makes sense. But what if we have a class LeftHandBoogie:
    Java Code:
    stopGoButton = new JButton("Boogie Down");
    that loads when the ui gets a button event? Then the static initializer may run whe the class is loaded and is the conceptual equivalent of initalizing the stack frame pointer so there should be only one per program. That would be of course unless the jvm runs the static initalizers for all classes that may be needed, iow the zero page AVL tree ( a self-balancing binary search tree that pages L2 ) may bring in the code, but does it branch and run the code before main is called, for all classes that may possibly be used.

    Basically, you moved ahead of me and illustrated someting to me I had not thought of but what if two threads load the same class?....

    Now what happens.

    Thus, the basis of my question.
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

  13. #13
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    7

    Default

    Having each class generate an internal instance counter that would allow each thread to see if the class had already been loaded would stop multiple loads from happening. (Assuming 2 threads don't reach the same class in such a time difference that the instance counter isn't incremented before the second thread loads it again)

    As for how the JVM builds the tree I'd assume it was designed to load each class that may be used to check for inconsistencies(some code within that program that loads a class already loaded) and overall program stability. Sacrifice some time and memory when you run the program instead of only loading a class when it's used and running the issue or a massive load time or not having enough memory to store it.

  14. #14
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Default

    ( cannot see all of reply - bump )

    Why and how stop other classes from loading?
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

  15. #15
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Arrow Load times

    If there is only one,... wow ~ this is getting interesting. Suffice it for now, it is known that without various tools - such a static load would run indeterminate, though each thread would only increment a counter:
    Java Code:
    static int instanceCounter = 0x0000;//
    static{++instanceCounter;}
    There still is no way to ++instanceCounter and read in without synchronization barriers. A static is, by definition, on the activation record ( stack ) thus doing ++instanceCounter would have each thread incrementing instanceCounter but what if in the constructor of BoogieBubba we do BoogieBubba(){if(instanceCounter > 99){print("get more beer");}Though only one thread can count the beers, the construcor would run at an indeterminate time clocking against static constructor..

    I did some work on load times, I think we as computer scientists have some sobering realizations awaiting in the comercial realm. I fiddled with load code and got the same millisecond count no matter what I did.

    I know for a fact, beyond the shadow of L-3 that what happens in commercial work is only similar to what happens in formal studies, often mechaincs of a machine are not what a student thinks they are.

    I do know that load times do not need to be what they are, we often have bloated code-wagons because people insist on machines running slowly, I did an overnight test recently generating AES keys, the machine runs much faster than I thought when the code is realistic. I had previously coded for some absurd key length, then dismissed init() times as an inevitable consequence of people.

    There was also another instace where I posted in a discussion asking about failure modes of Threads ~ I was so acclimatized to consumer-grade equipment runnning crappy that I went into the post on the assumption that trying to run two threads would break the machine

    I had to crawl back to reality.

    ( folks: L-3 is Lagrange points == astronomy, nothing to do with L-2 )

    { Hint: If you want to skip ahead on this, study "static factory method" }
    Last edited by Nicholas Jordan; 11-26-2008 at 01:40 AM. Reason: hint
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

  16. #16
    samashti is offline Member
    Join Date
    Nov 2008
    Posts
    1
    Rep Power
    0

    Default

    static means to assceess this methos any where no need to use the create the object.Thatswhy for Main method no need to create the object

  17. #17
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Lightbulb static factory methods

    Quote Originally Posted by samashti View Post
    static means to assceess this methos any where no need to use the create the object.Thatswhy for Main method no need to create the object
    Yes, but original poster arrived at:
    Why go through the extra hassle of figuring out every variable needed and then creating an initializer for them?
    which brings up fine point between static{} v
    Java Code:
    public static getInstance(){}
    which can bring up subtle timing issues. We can advance that to:
    Java Code:
    public static synchronized getInstance(){};//
    and
    Java Code:
    public static synchronized getInstance(int parameter){};//
    which extracts utility from the static facility that can be OO in the sense that it coagulates various constructor designs, allowing switching on the paramater in one place rather than having to re-write several constructors.
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •