Results 1 to 20 of 20

Thread: static keyword

  1. #1
    lala is offline Member
    Join Date
    Oct 2010
    Posts
    80
    Rep Power
    0

    Default static keyword

    Hello.
    I am new to java. I thought you only put one static statement in the code, "public static void main(String[] args)"

    But this code has more than one static statement.

    What is the difference between the first 2 static statements & the ""public static void main(String[] args)" statement? Why have both? Why not put the 1st two static statements under the public static... statement? Is this example trying to show me different ways of using static? Thanks In Advance.

    Java Code:
    import java.util.*;    
    public class Ex2_26 		//Pg. 75
    { 							// Beginning of class 
    	static final int NUMBER = 12;
    	static Scanner console = new Scanner(System.in);
    	public static void main(String[] args)
    	{
    		int firstNum;
    		int secondNum;
    		
    		firstNum = 18;
    		System.out.println("Line 11: firstNum = "
    						   + firstNum); 	// output the value of firstNum
    		System.out.print("Line 12: Enter an integer: ");
    		secondNum = console.nextInt(); // read & store the integer into the variable secondNum
    		System.out.println();
    		
    		System.out.println("Line 15: secondNum = "
    				   + secondNum);
    		
    		firstNum = firstNum + NUMBER + 2 * secondNum;
    		
    		System.out.println("Line 17: The new value of " +
    						   "firstNum = " + firstNum);	
    			
    		}
    }

  2. #2
    AcousticBruce is offline Senior Member
    Join Date
    Dec 2010
    Location
    Indiana
    Posts
    202
    Rep Power
    4

    Default

    Hey lala, good question. It helps so much to understand the logic doesn't it?

    Anyway I am relatively new to understanding this subject so I will do my best.

    Perhaps its trying to show you that those must be static in order for the main method to use them. Here is something more simple to look at.


    pubNum is not accessible. but the staticNum which is static is.

    Also you cannot declare a public private or static variable in the main method.
    Java Code:
    public class TestClass {
    
    	static int staticNum = 12;
    	public int publicNum = 24
    
        public static void main(String[] args)	{
            System.out.println(staticNum); [COLOR="Red"]// this works[/COLOR]
            System.out.println(publicNum); //[COLOR="Red"] this does NOT work. [/COLOR]
        }
    
    }
    Why is the main method static? This is probably out of my league right now.
    I tried googling it and found some interesting stuff. It just seems a bit out of my league right now.

  3. #3
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Im also fairly new but here is what I have to say. I believe this is a fairly accurate explanation, although, I am sure a more experienced programmer will explain it better.

    Static allows a method to be used by multiple objects.

    Lets say you create a static method called Print, which really just allows you to use the words print("some item"); instead of System.out.println("blah"); in order for the static item to be used anywhere it needs to be static.
    To create the print method you would create a class called Print which has all the overloaded definitions of print. Normally if you wanted to use a method from a class, you would have to create an instance of that class:
    Java Code:
    Print x = new Print();
    static allows you to use the method without an instance of the object.

    The static keyword is a bit challenging for me to explain, I understand it though.

    The ‚€œstatic‚€Ě Keyword In Java

    This link might be useful to you.

    static comes in handy for utility type methods:
    Java Code:
    class RandomClass
    {
      public static int mult3(int x, int y, int z)
      {
         return x * y * z;
       }
    }
    
    public class Blah
    {
    public static void main(String[] args)
    {
        System.out.println(mult3(10, 20, 5);
    }
    }
    You can make a call to that method without creating an object first.
    Last edited by sunde887; 01-08-2011 at 09:58 PM.

  4. #4
    AcousticBruce is offline Senior Member
    Join Date
    Dec 2010
    Location
    Indiana
    Posts
    202
    Rep Power
    4

    Default

    It really can get pretty complex trying to explain static.

    When you are dealing with multiple classes and polymorphism, I can see where static really gets useful.

    Have you messed with multiple classes and creating objects yet?

    If not that's ok. You can practice LOTS of stuff without understanding static. Once you start learning more basics you go back to an area you were having trouble and for some reason it makes more sense.

  5. #5
    Iron Lion is offline Senior Member
    Join Date
    Nov 2010
    Posts
    210
    Rep Power
    5

    Default

    Quote Originally Posted by AcousticBruce View Post
    Why is the main method static? This is probably out of my league right now.
    The main method needs to be static because the JVM calls it before any objects exist.

  6. #6
    lala is offline Member
    Join Date
    Oct 2010
    Posts
    80
    Rep Power
    0

    Default static keyword

    Thanks for responding AcousticBruce, IronLion, & sunde887.

    Great input, & lots for me to gnaw on. :-) As my foray ino the world of Java progresses, I'm sure I will understand better.
    Thanks again. :)

  7. #7
    Join Date
    Jul 2010
    Posts
    12
    Rep Power
    0

    Default

    Hello lala,

    ' static ' is a keyword used to represent a class level variable or method .

    You can access those variables or methods by using your classname directly.

    Even you can access them by the object of that class like nonstatic members.

    But the main difference between static & non static variables & methods is :

    In static mode :

    the change updated by one object can reflect to the value which will be used by all rest of the objects...

    where as , the nonstatic variables are concern , there is a seperate copy for each and every object...

    Here the key points which can helps you a lot ...

    1.
    From non static block , you can access both static & nonstatic members of the class.

    2 . From the static block , you can access only static members of the class.

    Here members in the sense , both variables and methods ....

  8. #8
    lala is offline Member
    Join Date
    Oct 2010
    Posts
    80
    Rep Power
    0

    Default static keyword

    Thanks AnanthNag.

    Soooo, in my example why have both? Why not put the 1st two static statements under the public static... statement?

    Thanks

  9. #9
    lala is offline Member
    Join Date
    Oct 2010
    Posts
    80
    Rep Power
    0

    Lightbulb static keyword (ahhhhh... i get it)

    After more reading & playing, i get "static".

    thanks everyone.

  10. #10
    Jodokus's Avatar
    Jodokus is offline Senior Member
    Join Date
    Jan 2011
    Location
    Amsterdam, the Netherlands
    Posts
    230
    Rep Power
    4

    Default

    It's no public static statement but a method-declaration (of the main method).
    The first two static declarations (and initializations) are global statics. They have (if properly declared private which they are not) global scope in the class (now in the package). Maybe console needs applicationwide scope, than make it public. Other variables, like firstnum, have method-scope. There is no limit on the number of statics as you suggested, but most variables are bound to instances of a class, not to the Class as such, like others explained already.
    There are properties of cats in general (mean and furry) and of a particular cat (sweet).

  11. #11
    lala is offline Member
    Join Date
    Oct 2010
    Posts
    80
    Rep Power
    0

    Default (Solved) static keyword

    yes, yes Jodokus. I'm grinning from ear to ear, because i understand what u r saying.

    The 1st two static static statements will be accessible throughout the program.

    Ahhhhh...Understanding. It's a beautiful thing.

  12. #12
    AcousticBruce is offline Senior Member
    Join Date
    Dec 2010
    Location
    Indiana
    Posts
    202
    Rep Power
    4

    Default

    Hey Lala,

    This might help you see static in a new light.

    there is two variable one is static inGarage and one public thisType. Notice how one counts up an inGarage keeps going up while thisType is doesn't. This is because thisType is not static and has a separate thisType varaible for each object. There is only one static variable inGarage that they all share.


    I used polymorphism to extend Vehicle class, that is what all the extra classes are for... if you do not understand this topic, do not worry, just worry about the static and public variables at least in this example :)
    Java Code:
    public class Main {
    
        public static void main(String[] args)	{
    
            System.out.println();
            Vehicle[] vehicle = new Vehicle[5];
            vehicle[0] = new Car();
            vehicle[1] = new Truck();
            vehicle[2] = new Truck();
            vehicle[3] = new Truck();
            vehicle[4] = new Van();
    
            System.out.println();
            System.out.printf("You have %d total vehicles", Vehicle.inGarage);
            System.out.println();
    
    
    
        }
    }
    Vehicle class code.
    Java Code:
    public class Vehicle {
    
        public int thisType = 0; // change this from public to static if you want.
        static int inGarage = 0; // if you change this you get an error because of Vehicle.inGarage in main method.
    
        Vehicle() {
            inGarage++;
            thisType++;
            System.out.printf("%d new %s and ", thisType, this.getClass().toString().substring(6));
            System.out.printf("%d total", inGarage);
            System.out.println();
        }
    }
    class Van extends Vehicle {
    }
    class Car extends Vehicle {
    }
    class Truck extends Vehicle {
    }
    Last edited by AcousticBruce; 01-11-2011 at 03:22 PM.

  13. #13
    Jodokus's Avatar
    Jodokus is offline Senior Member
    Join Date
    Jan 2011
    Location
    Amsterdam, the Netherlands
    Posts
    230
    Rep Power
    4

    Default

    @AcousticBruce:
    At first I thought your program was wrong (I looked at the code and thought, "this isn't working", only then I saw that you instructed OP to change static for public). Now I think it's confusing because the variable is called "carsInGarage" in stead of "vehiclesOfThisKindInGarage".
    @OP:
    public static variables have a special role because once initialized they are seen everywhere and always in your program ("always" means: you don't first have to make a new class instance to access the variable).
    There are also static methods. They are often little tool-methods found in libraryclasses and just do something irrespective of the containing class, like in the old days before Object Oriented Programming.

  14. #14
    goldest's Avatar
    goldest is offline Senior Member
    Join Date
    Oct 2009
    Location
    Pune, India
    Posts
    469
    Rep Power
    6

    Wink

    As everyone is going static, I would like to discuss one more use of static keyword.

    There are "static" initializers in java, also known as static blocks. They get loaded at the time of class loading and can be used for class initialization stuff as per your need.

    The syntax is,

    Java Code:
    static {  }

    Have a look at the following simple example,

    Java Code:
    public class StaticInitializer {
    	public static void main(String args[]) {
    	}
    
    	static {
    		System.out.println("I will load before anything else in this class.");
    	}
    }
    The main method does nothing, but when you run this, the contents inside static block will get executed.

    Just for fun,

    Goldest
    Java Is A Funny Language... Really!
    Click on * and add to member reputation, if you find their advices/solutions effective.

  15. #15
    AcousticBruce is offline Senior Member
    Join Date
    Dec 2010
    Location
    Indiana
    Posts
    202
    Rep Power
    4

    Default

    Quote Originally Posted by Jodokus View Post
    @AcousticBruce:
    At first I thought your program was wrong (I looked at the code and thought, "this isn't working", only then I saw that you instructed OP to change static for public). Now I think it's confusing because the variable is called "carsInGarage" in stead of "vehiclesOfThisKindInGarage".
    ...
    I can see where you are coming from. The main idea was to just count the new Vehicles. When it is static it does just that.
    i just edited the code so it makes more sense... please let me know if this is confusing, that is the last thing I wanted to do.



    Main
    Java Code:
    public class Main {
    
        public static void main(String[] args)	{
    
            System.out.println();
            Vehicle[] vehicle = new Vehicle[5];
            vehicle[0] = new Car();
            vehicle[1] = new Truck();
            vehicle[2] = new Truck();
            vehicle[3] = new Truck();
            vehicle[4] = new Van();
    
            System.out.println();
            System.out.printf("You have %d total vehicles", Vehicle.inGarage);
            System.out.println();
    
    
    
        }
    }


    Vehicle and extending classes
    Java Code:
    public class Vehicle {
    
        public int thisType = 0; // change this from public to static.
        static int inGarage = 0; //
    
        Vehicle() {
            inGarage++;
            thisType++;
            System.out.printf("%d new %s and ", thisType, this.getClass().toString().substring(6));
            System.out.printf("%d total in garage.", inGarage);
            System.out.println();
        }
    }
    class Van extends Vehicle {
    }
    class Car extends Vehicle {
    }
    class Truck extends Vehicle {
    }
    Last edited by AcousticBruce; 01-11-2011 at 03:24 PM.

  16. #16
    Jodokus's Avatar
    Jodokus is offline Senior Member
    Join Date
    Jan 2011
    Location
    Amsterdam, the Netherlands
    Posts
    230
    Rep Power
    4

    Default

    Hello AcousticBruce
    I'm very confused, but not about your new code, that looks good.
    No offence, but I'm confused because your code in the thread upon which I reacted has also changed in the new version. That version had no subclasses and made new Vehicles. I keep rechecking. Have senior members the power to change history in the thread? I really not get it.

  17. #17
    Jodokus's Avatar
    Jodokus is offline Senior Member
    Join Date
    Jan 2011
    Location
    Amsterdam, the Netherlands
    Posts
    230
    Rep Power
    4

    Default

    Hello AcousticBruce

    Correction, I made a mistake. I see that I too have the power to edit my contributions. (I'm rather new to forums.) But is it the right way to do? Should a thread not mirror the history of discussions, except gross (writing-)errors? No one now knows what I reacted on.
    But maybe now I'm going to correct stupid embarrassing remarks I made in other threads ;>)
    Last edited by Jodokus; 01-11-2011 at 07:21 PM. Reason: tread to thread

  18. #18
    lala is offline Member
    Join Date
    Oct 2010
    Posts
    80
    Rep Power
    0

    Default (solved) static keyword

    Acoustic, i will check out your code and let you know the results.

    Many thanks

  19. #19
    AcousticBruce is offline Senior Member
    Join Date
    Dec 2010
    Location
    Indiana
    Posts
    202
    Rep Power
    4

    Default

    Quote Originally Posted by Jodokus View Post
    Hello AcousticBruce

    Correction, I made a mistake. I see that I too have the power to edit my contributions. (I'm rather new to forums.) But is it the right way to do? Should a thread not mirror the history of discussions, except gross (writing-)errors? No one now knows what I reacted on.
    But maybe now I'm going to correct stupid embarrassing remarks I made in other threads ;>)
    Actually you are right. I like that philosophy. That makes perfect sense. I will from now on not go back and change my posts, because it can confuse and that is what new posts are for.

  20. #20
    Jodokus's Avatar
    Jodokus is offline Senior Member
    Join Date
    Jan 2011
    Location
    Amsterdam, the Netherlands
    Posts
    230
    Rep Power
    4

    Default

    @AcousticBruce,
    Thanks for the reply. Maybe make it static, for the world to know :>)

    Jodokus

Similar Threads

  1. Replies: 7
    Last Post: 09-24-2010, 06:09 AM
  2. Replies: 3
    Last Post: 02-11-2010, 10:59 AM
  3. use of static keyword
    By venkatallu in forum New To Java
    Replies: 2
    Last Post: 06-25-2009, 08:53 AM
  4. Replies: 1
    Last Post: 08-07-2007, 06:05 AM
  5. Replies: 1
    Last Post: 08-01-2007, 10:25 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
  •