Results 1 to 7 of 7
  1. #1
    ajetrumpet is offline Member
    Join Date
    Feb 2013
    Posts
    57
    Rep Power
    0

    Default static usage of variables (criteria )

    Guys, I'm a bit confused by this. I'm looking to patternize all of this stuff. For instance, I have the following code:

    Java Code:
    public class test
    {
    
       public static void main (String [] args)
       {
    
          final int x = 1;
          final int y = 2;
    
             if (x != y) { System.out.println("x is not equal to y"); }
    
       }
    
    }
    if I put the constants in the class hierarchy instead of in the method hierarchy, I get the error "static variable cannot be used in non-static context". Is there anyway that I can document constants, variables and objects, *where* they are placed and what operations are legal based on *where* I place them?

    Would someone be able to summarize this? The documentation is a bit long and I'm not sure I want to read through it all just to find little information like this. Any help? Thanks guys.

  2. #2
    pbrockway2 is online now Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,573
    Rep Power
    12

    Default Re: static usage of variables (criteria )

    You have declared main() as "static" and, as such, its definition (everything between the curly braces) is regarded as a "static context". A significant restriction on a static context is that you can only use variables from the class that are themselves static. That makes sense, if you think about it: marking main() as static means that main() is associated with the class as a whole and not any particular object. Consequently any (non local) variables in the main method had also better be static because, within main(), there is no particular object for them to be associated with.

    To illustrate, we cannot say:

    Java Code:
    public class Test
    {
            // foo is associated with a particular object
            // ie, it is the foo of some particular instance
        int foo = 42; 
     
        public static void main (String [] args)
        {
                // error!  The compiler sees "foo", but has no idea what
                // instance you are referring to.
            System.out.println(foo);  
        }
    }
    The compiler expresses its perplexity "whose foo?!" with the standard error message "non-static variable foo cannot be referenced from a static context".

    I'm not at all sure what might have led to the message you posted - because static variables are quite able to be used in non static contexts. A non static method is associated with a particular instance, but that doesn't hinder it being a context that uses variables that are associated with the class as a whole (ie are static). If it wasn't a typo, post code.

    ---

    Is there anyway that I can document constants, variables and objects, *where* they are placed and what operations are legal based on *where* I place them?
    I'm not really sure I understand this.

    Variables, methods and classes (and interfaces) can be static, final and have access modifiers. Additionally classes and interfaces belong to packages. And can be nested one inside another. There's a bewildering array of nuances of meaning that can be expressed by the various combinations each allowing certain types of access and disallowing others. As you pose it your question is too general to admit a (useful) answer: it's a bit like asking "Is there some way I can use the grammar of English to tell a story". The correct, but unuseful, answer is "yes".

    ---

    The class should be Test with an uppercase T.

  3. #3
    ajetrumpet is offline Member
    Join Date
    Feb 2013
    Posts
    57
    Rep Power
    0

    Default Re: static usage of variables (criteria )

    Quote Originally Posted by pbrockway2 View Post
    Java Code:
    public class Test
    {
            // foo is associated with a particular object
            // ie, it is the foo of some particular instance
        int foo = 42; 
     
        public static void main (String [] args)
        {
                // error!  The compiler sees "foo", but has no idea what
                // instance you are referring to.
            System.out.println(foo);  
        }
    }
    The compiler expresses its perplexity "whose foo?!" with the standard error message "non-static variable foo cannot be referenced from a static context".
    can it be said then that a static variable should be present if it is going to be used in a static method?

    I'm not at all sure what might have led to the message you posted - because static variables are quite able to be used in non static contexts. A non static method is associated with a particular instance, but that doesn't hinder it being a context that uses variables that are associated with the class as a whole (ie are static).
    so what I'm hearing is that the word "static", when its applied to anything that it can be applied to, means that whatever "thing" is static can only belong to the class in which it is contained. yes? is that the general meaning of "static"??

    Variables, methods and classes (and interfaces) can be static, final and have access modifiers. Additionally classes and interfaces belong to packages. And can be nested one inside another.
    that's EXTREMELY useful. there's a hierarchy there (packages => classes / interfaces => (what comes next in the hierarchy?).

    There's a bewildering array of nuances of meaning that can be expressed by the various combinations each allowing certain types of access and disallowing others.
    yes there is. That's one of the problems working with other developers. Terms get thrown around too much, which confuses everyone. Not much can be done about it, but it's worth knowing that the problem exists. The only hope we have though is that other developers will accept working by using the same terminology as everyone else, regardless of what conventions are put in place.

  4. #4
    pbrockway2 is online now Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,573
    Rep Power
    12

    Default Re: static usage of variables (criteria )

    can it be said then that a static variable should be present if it is going to be used in a static method?
    Yes.

    In the code I posted the variable foo should be static to avoid problems with its use in the static main() method. Nonstatic variables are fine, but only as part of some larger expression that makes it clear what instance is involved:

    Java Code:
    public class Test
    {
        static int foo = 42;
        int bar = 666;
      
        public static void main (String [] args)
        {
                // ok because foo is not associated with any particular instance
            System.out.println(foo);  
    
            Test test = new Test();
                // ok because the instance associated with bar (ie test)
                // is an explicit part of the expression test.bar
            System.out.println(test.bar);
        }
    }
    so what I'm hearing is that the word "static", when its applied to anything that it can be applied to, means that whatever "thing" is static can only belong to the class in which it is contained. yes? is that the general meaning of "static"??
    I prefer to say that static methods and variables of a class are associated with the class and not with a particular instance. They represent properties (variables) and behaviour (methods) of the class not of instances of the class. Such static things are not common and it's hard to give a compelling example of them. But consider dogs which happen by some law or other to have registration ids associated with them. It is intended that the ids be unique.

    Java Code:
    class Dog {
        static int nextId = 0;
    
        int id;
        String name;
    
        Dog(String name) {
            this.name = name;
            id = nextId++;
        }
    }
    id is a property of this or that particular dog. But nextId is not - rather it is implemented here as a property of Dogness-in-general. (It might well be implemented some other way: for instance there could be a DogRegistrationBureau class which assigns id numbers and nextId would be an ordinary, non static, variable of this class.)

    there's a hierarchy there (packages => classes / interfaces => (what comes next in the hierarchy?).
    Classes belong to (ie are part of) packages, and contain methods/variables/nested classes. But I wouldn't think of that as constituting a hierarchy. You could do, but it strikes me that a hierarchy should be homogeneous and this is not: being part of a package is not at all like being declared within a class.

    Terms get thrown around too much, which confuses everyone. Not much can be done about it, but it's worth knowing that the problem exists.
    I don't see the complexity as a problem. (No more with Java than with the rather more complex English.) Being expressive involves being complex and being expressive is not problematic, just difficult. I don't understand all the details of Java's syntax and I don't claim to, rather I start with some particular task I want to do and try to find a natural seeming way of going about it. (more on "natural" later). If I can't come up with something, or I come up with something ugly and clumsy, I google or I ask at places like this.

    As for terms being thrown around: look 'em in the eye and ask "what do you mean?" Do your bit to stamp out the CS BS. Occasionally, of course, your interlocutor will mean something specific and they will say what they mean.

    ---

    I would offer a couple of "rules of thumb" for Java syntax if you're starting out:

    (1) Avoid "static". The main method *must* be static, but often (usually) nothing else need be. Associating state and behaviour with instances (things) and not with classes (types of thing) leads to a great deal of simplicity and shouldn't be given up lightly. If you finding yourself "having" to make something static that's just the sort of ugliness that I suggest you investigate or ask about.

    (2) Avoid nesting types. (declaring classes inside other classes) I mentioned them only because they are part of the real answer to your question "Is there anyway that I can document constants, variables and objects, *where* they are placed and what operations are legal based on *where* I place them?" where I interpreted "document" as "express". I am *not* advocating you race into using them: you can go along way without having to learn the intricacies of nested types.

    I guess what I'm saying is that you should start with *your* specific problem and not with the generalities of Java syntax a whole. And keep thing things "simple" as they say - not the best word perhaps: but we only have words for its opposite (ugly, contrived). Sometimes the best might be a little complex (I think Einstein remarked that theories should be as simple as possible, but no simpler). You just have to develop a sense for what feels "right" or "fitting". Again, ask if you get stuck and don't forget to describe both the specific thing you are trying to express, and whatever code it is you have come up with.

  5. #5
    ajetrumpet is offline Member
    Join Date
    Feb 2013
    Posts
    57
    Rep Power
    0

    Default Re: static usage of variables (criteria )

    pb,

    the insight was incredibly helpful. nice job. hopefully mine was too. there is something to be learned fro my talk as well, as I'm giving you some insight here as to how thought leaders perceive development (and as such, developers).

    hopefully that helps you work well with your counterparties, if you currently have some.

  6. #6
    pbrockway2 is online now Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,573
    Rep Power
    12

    Default Re: static usage of variables (criteria )

    You're welcome. And yes, what you said was thought provoking and worth saying.

    I'm just an amateur and, so, don't have anywhere but here to express my ideas. (My colleagues are highschool teachers, and it oftentimes seems pointless telling them *anything*...). Also I've just started a Coursera (MOOC) course on writing compilers, and that obliges me to think quite differently - not trying to write my simple programs correctly and with whatever "elegance" I can manage, but trying to think precisely and comprehensively about a language as a whole. Even for a toy language that's not easy!

  7. #7
    ajetrumpet is offline Member
    Join Date
    Feb 2013
    Posts
    57
    Rep Power
    0

    Default Re: static usage of variables (criteria )

    Quote Originally Posted by pbrockway2 View Post
    You're welcome. And yes, what you said was thought provoking and worth saying.

    I'm just an amateur and, so, don't have anywhere but here to express my ideas. (My colleagues are highschool teachers, and it oftentimes seems pointless telling them *anything*...). Also I've just started a Coursera (MOOC) course on writing compilers, and that obliges me to think quite differently - not trying to write my simple programs correctly and with whatever "elegance" I can manage, but trying to think precisely and comprehensively about a language as a whole. Even for a toy language that's not easy!
    Well, if you figure out how to write a good compiler that isn't a piece of junk and trustworthy, maybe you can substitute it in for some of Microsoft's crap? :) YEAH. Specifically, I know that VB6's compiler needs to be trashed. But then again, that won't be around for very much longer anyway.

Similar Threads

  1. I can't able to see static variables:(
    By yuzi123 in forum New To Java
    Replies: 5
    Last Post: 11-24-2011, 07:36 AM
  2. Replies: 6
    Last Post: 02-15-2010, 05:31 AM
  3. What are Instance variables and static variables?
    By sandeshforu in forum New To Java
    Replies: 3
    Last Post: 09-09-2009, 06:48 PM
  4. Using Static Variables
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-17-2008, 12:08 AM
  5. Help with static variables
    By bbq in forum Advanced Java
    Replies: 1
    Last Post: 06-28-2007, 06:38 PM

Posting Permissions

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