Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: Difference with static and non static variables

  1. #1
    Junior Member SkynetSystems's Avatar
    Join Date
    Aug 2011
    Location
    England
    Posts
    9
    My Mood
    Mellow
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Difference with static and non static variables

    Hello, I am very new to Java and was going through the Oracle tutorial. I got to the variables page and have got stuck on understanding the difference between static and non-static variables.

    I am using the famous Bicycle object as an example. The class defines non static variables and from what the Java definition is of a non static variable, I was under the impression that this means no matter how many objects you create from this class, they will all have their own values even when the variable is manipulated in various objects.

    Here is Java's definition:
    Instance Variables (Non-Static Fields) Technically speaking, objects store their individual states in "non-static fields", that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); the currentSpeed of one bicycle is independent from the currentSpeed of another.Instance Variables (Non-Static Fields) Technically speaking, objects store their individual states in "non-static fields", that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); the currentSpeed of one bicycle is independent from the currentSpeed of another.

    And the example code:
    package Bicycle;
     
    public class Bicycle {
        int cadence = 0;
        int speed = 0;
        int gear = 1;
     
        void changeCadence(int newValue){
            cadence = newValue;
        }
     
        void changeGear(int newValue){
            gear = newValue;
        }
     
        void speedUp(int increment){
            speed = speed + increment;
        }
     
        void applyBrakes(int decrement){
            speed = speed - decrement;
        }
     
        void printStates(){
            System.out.println("Cadence: "+cadence+" Speed: "+speed+" gear: "+gear);
        }
     
     
    }

     
    package Bicycle;
     
    public class BicycleDemo {
        public static void main(String[] args){
            Bicycle bike1 = new Bicycle();
            Bicycle bike2 = new Bicycle();
     
            bike1.changeCadence(50);
            bike1.speedUp(10);
            bike1.changeGear(2);
            bike1.printStates();
     
            bike2.changeCadence(50);
            bike2.speedUp(2);
            bike2.changeGear(2);
            bike2.changeCadence(40);
            bike2.speedUp(10);
            bike2.changeGear(3);
            bike2.printStates();
        }
    }

    From what Java states about static variables, I thought the static modifier acted the same how the '&' in PHP in that it would create a reference. Java states that when declared it tells java that there is exactly 1 copy of the variable in existence. I thought this means if you change a value in one object, it would set the same value in the other object.

    So, I added the static keyword to all variables when declared but I get the exact same result. Am I completely getting the wrong idea?

    Please help!

    Regards,

    SS


  2. #2
    Junior Member
    Join Date
    Jan 2013
    Posts
    20
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: Difference with static and non static variables

    Hi , i understand your proble. For static modifier, just declare the all variables as static and in the main() just add the code after bike2.printStates() like bike1.printStates() and run it, in this we got bike2 object result. It mean whenever you perform the modification on bike2 those modifications are effected to bike1, because the static variables are common for all objects to the same class.

  3. #3
    Forum VIP
    Join Date
    Oct 2010
    Posts
    275
    My Mood
    Cool
    Thanks
    32
    Thanked 54 Times in 47 Posts
    Blog Entries
    2

    Default Re: Difference with static and non static variables

    What you are doing probably is working (although strongly discouraged because of the nature of a bikes variables), but you are printing bike 1's states before bike 2 begins its edits, hence why you are getting the same results.

    However, that is not a very good example of static non-constant variables. A lot of the time these things can be tricky, and most of the time they can be replaced with better design. Here is one example where static non-constants would be a reasonable solution to the problem:

    Suppose you have a resources class that has a few hashmaps containing things like sound, images, file locations, whatever. This is going to be needed in the entire graphical part of your code, so passing an instance around isn't very eloquent. Also, resources is unlikely after initialization, and is never going to be instanced twice. Both of those are use tips that some type of static construct is going to be optimal.

    Then, there are two choices. The main class (Most running packages have them, eg the Frame extension, or the class containing the game loop in LWJGL, or the BasicGame in Slick2d, whatever) will either have a static variable containing that resources variable, or you can make the methods/variables in Resources static (This is what I do/would do) That way, without passing an instance through each constructor, anyone needing access to the resources can use one of the following

    Image blahblah = Game.getResources().getImage("blahblah.png")
    // or
    Image blahblah = Resources.getImage("blahblah.png")

  4. #4
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: Difference with static and non static variables

    Quote Originally Posted by SkynetSystems View Post
    ...

    I am using the famous Bicycle object as an example. The class defines non static variables and from what the Java definition is of a non static variable, I was under the impression that this means no matter how many objects you create from this class, they will all have their own values even when the variable is manipulated in various objects.
    That's right. For non-static variables, each object has its very own copy of that variable

    Quote Originally Posted by SkynetSystems View Post
    .Java states that when declared it tells java that there is exactly 1 copy of the variable in existence. I thought this means if you change a value in one object, it would set the same value in the other object.
    That's right: For static variables, all objects have the same value of that variable. A static class variable is not associated with any particular object.

    So, I added the static keyword to all variables when declared but I get the exact same result. Am I completely getting the wrong idea?
    I think you have the right idea, but your code doesn't illustrate the principle.

    Try the following with the original (non-static variable version) Bicycle class::
        public static void main(String [] args) {
            Bicycle bike1 = new Bicycle();
            Bicycle bike2 = new Bicycle();
     
            bike1.changeCadence(50);
            bike1.speedUp(10);
            bike1.changeGear(2);
            System.out.print("After setting bike1 thingies, calling bike1.Printstates():\n    ");
            bike1.printStates();
     
            bike2.changeCadence(50);
            bike2.speedUp(2);
            bike2.changeGear(2);
            bike2.changeCadence(40);
            bike2.speedUp(10);
            bike2.changeGear(3);
            System.out.print("\nAfter setting bike2 thingies, calling bike2.Printstates():\n    ");
            bike2.printStates();
     
            System.out.print("\nCalling bike1.printStates() again:\n    ");
            bike1.printStates();
        }


    Output:

    After setting bike1 thingies, calling bike1.Printstates():
        cadence:50 speed:10 gear:2
     
    After setting bike2 thingies, calling bike2.Printstates():
        cadence:40 speed:12 gear:3
     
    Calling bike1.printStates() again:
        cadence:50 speed:10 gear:2


    Now go back and declare all of the variables in the Bicycle class to be static. Don't make any changes to BicycleDemo.java

    Output:
    After setting bike1 thingies, calling bike1.Printstates():
        cadence:50 speed:10 gear:2
     
    After setting bike2 thingies, calling bike2.Printstates():
        cadence:40 speed:22 gear:3
     
    Calling bike1.printStates() again:
        cadence:40 speed:22 gear:3


    Of course this is just for purposes of testing your understanding of the "static" thing. If you had two Bicycle objects you would, obviously, not want them to have the same cadence, speed and gear settings, so it wouldn't make sense to declare them static in the Bicycle class definition.


    Cheers!

    Z

  5. #5
    Junior Member SkynetSystems's Avatar
    Join Date
    Aug 2011
    Location
    England
    Posts
    9
    My Mood
    Mellow
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Difference with static and non static variables

    Zaphod thank you so much for breaking that down into simple terms for me. I understand the difference a lot better than before. Obviously I'm sure there is more to learn but I just needed to grasp the basic concept first.

    It's the same as a reference variable in PHP then in that if you change the value to reference, it changes the value of the original.

    Thank you all for your help.

    Kind regards,

    SS

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Difference with static and non static variables

    if you change the value to reference, it changes the value of the original.
    Not sure that is the right concept. Not sure what you mean by reference and by original.
    With a static variable, there is only one variable for the class, not one variable for each instance of the class.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member SkynetSystems's Avatar
    Join Date
    Aug 2011
    Location
    England
    Posts
    9
    My Mood
    Mellow
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Difference with static and non static variables

    Let's say we have a php variable. You create a reference like so:
    $var = 0;
    $new = &$var;

    Here I set $new to point to the same memory as $var so if I make any changes to $new, it also changes the value in the original $var variable whereas if I leave off the ampersand before $var, it creates it's own separate copy of the value, so changing $new will not affect $var, which is similar to instance variables?

    I've only just really been able to get on today and I've just looked again at the docs. Can I think of static variables as pointing to the same memory address in all instances of the variable, be it manipulated in the same object or a second object from the same class? For the example above, we create 2 objects from the same class and when declared with static, they both have the same value when printed.

    It might be the wrong concept to think of static variables as references but I think they work in a very similar way in comparison to my PHP example.

    Am I right in saying this or totally off the mark?

    I know it's been answered but I want to really understand it before moving on because I'll just get to a stage where I won't know what I'm declaring and why.

    Kind regards,

    SS.

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Difference with static and non static variables

    static variables are variables that exist for the class and not just in instances of the class.
    I don't see where references are related to that.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Replies: 4
    Last Post: November 15th, 2012, 12:09 AM
  2. private static variables
    By tcstcs in forum Java Theory & Questions
    Replies: 4
    Last Post: June 28th, 2012, 01:00 AM
  3. What's the difference between a static and non-static method?
    By wholegrain in forum Java Theory & Questions
    Replies: 4
    Last Post: February 23rd, 2012, 01:06 AM
  4. Non-Static variables
    By liloka in forum What's Wrong With My Code?
    Replies: 3
    Last Post: December 31st, 2010, 09:13 AM
  5. Replies: 10
    Last Post: September 6th, 2010, 04:48 PM