Results 1 to 5 of 5
Like Tree2Likes
  • 2 Post By quad64bit

Thread: Some Help with Static variables and methods

  1. #1
    ankiit is offline Member
    Join Date
    Dec 2011
    Location
    India
    Posts
    74
    Rep Power
    0

    Default Some Help with Static variables and methods

    Hi Mentors,

    I am finding the usage of static keyword a bit difficult to understand, please share your experience with the keyword and some good references to the same.

    Thanks in advance,
    Ankit

  2. #2
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default Re: Some Help with Static variables and methods

    So static is the keyword which tells java that something should be a class variable or a class method... a non-static version being an instance variable or an instance method. What does this mean?

    Well, class methods are accessible globally without requiring an instance of the class to use it. For instance, if we had a class called "MyMath" with some instance methods:

    Java Code:
    public class MyMath{
        public int add(int a, int b){
            return a+b;
        }
    }
    then the only we we could use the add method would be to have an instance of MyMath first like so:

    Java Code:
    public class Fun{
        public static void main(String[] args){
            MyMath math = new MyMath();
            System.out.println(math.add(2,5));
        }
    }
    Now, if we had made the method static, then we could use the add method simply by invoking the name of the class, since it is a 'class' method:

    Java Code:
    public class MyMath{
        public static int add(int a, int b){
            return a+b;
        }
    }
    
    public class Fun{
        public static void main(String[] args){
            System.out.println(MyMath.add(2,5));
        }
    }
    So when would we ever not make something static? Good question, and the answer is 'almost always'. You see, this class method is great for something like our add method, or Math.pi (part of the java class lib), or Color.RED, etc... However, most of the time, we're dealing with unique objects who's methods only make sense in the context of that particular instance of a class.

    For instance, lets say we were making a database of sorts, and had a class called "Person".

    Java Code:
    public class Person{
        private String name;
    
        public Person(String name){
            this.name = name;
        }
    
        public String getName(){
            return name;
        }
    }
    If we wanted to retrieve the person's name, we could call 'getName()'. Now if getName() were static, and we had a million people in our database, who's name would Person.getName() return? There in lies the problem. Each person has a unique name, so a class (static) method/variable is not appropriate.

    TLDR; Don't use static except for the main() method unless you know why you are using it, and have a very good reason for doing so!
    Last edited by quad64bit; 01-11-2012 at 04:52 AM.
    Fubarable and ankiit like this.

  3. #3
    ankiit is offline Member
    Join Date
    Dec 2011
    Location
    India
    Posts
    74
    Rep Power
    0

    Default Re: Some Help with Static variables and methods

    Hi quad64bit,

    Thanks a lot for the information.

    Are the static variables/methods called even before main?

    I was going through a code in a book, the code is as follows:-

    Java Code:
    class UseStatic
    {
    	static int a = 3;
    	static int b;
    	
    	static void meth(int x)
    	{
    		System.out.println("x is::" + x);
    		System.out.println("a is::" +a);
    		System.out.println("b is::" +b);
    		
    	}
    	static{
    		System.out.println("Static Block initialized");
    		System.out.println("initializing b");
    		b =a *4;
    	}
    	public static void main(String[] args)
    	{
    		System.out.println("In the main");
    		meth(42);
    	}
    }
    and the output is as follows:-

    /* OUTPUT
    Static Block initialized
    initializing b
    In the main
    x is::42
    a is::3
    b is::12
    */

    But when i use main in another class, the output changes,

    the code is as below:-
    Java Code:
    class Statict
    {
    	static int a = 3;
    	static int b;
    	
    	static void meth(int x)
    	{
    		System.out.println("x is::" + x);
    		System.out.println("a is::" +a);
    		System.out.println("b is::" +b);
    		
    	}
    	static{
    		System.out.println("Static Block initialized");
    		System.out.println("initializing b");
    		b =a *4;
    	}
    	
    }
    class UseStatic
    {
    	public static void main(String[] args)
    	{
    		System.out.println("In the main");
    		Statict.meth(42);
    	}
    }
    and the output for this code is as below:-

    /*OUTPUT
    D:\rarework\Practice>java UseStatic
    In the main
    Static Block initialized
    initializing b
    x is::42
    a is::3
    b is::12
    */

    Why is there a change in the output?

    I have one more question, regarding "why we have defined the access interface of the constructor as public".

    Thanks in advance. :)

    kind regards,
    Ankit

  4. #4
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default Re: Some Help with Static variables and methods

    Are the static variables/methods called even before main?
    They're only called if you call them. Nothing happens by itself.

    static{
    System.out.println("Static Block initialized");
    System.out.println("initializing b");
    b =a *4;
    }
    The static block is an initializer that can use used to initialize static variables in a class that consists purely or partially of static content. You generally do not need to use it, and shouldn't for most day to day apps.

    But when i use main in another class, the output changes,
    You always need a main method, but just 1 per program. You could have a thousand classes, but main is the entry point for the entire app. Only 1 of your classes should have one. In your first case, the main method is in the class in question. Since static blocks are executed during class initialization, you see the block happen first. Once the class is initialized, then the main method executes. In the second example, you do not have a static block in the current class, so you see the main first, and then you call the class with the static block. It is initialized, and then you see it's output.

    I have one more question, regarding "why we have defined the access interface of the constructor as public".
    First off, with questions like this, you should always try it an see! Basically, if a constructor is private, it prevents other classes from instantiating the said class. This is useful if you are making a purely static class which will only be used in a static context. Again, I want to point out that this is a very special design pattern which you don't want to use for most of what you want to do.

    Static can be handy for global shared data (this can be problematic too, so you have to be careful) and it is useful for methods which are context free and always function a certain way. The methods and fields in the Math class are a great example - Math.pi or Math.pow() always work the same way, so making them static makes sense. most of your object oriented code however will focus on unique instances of classes, so static isn't helpful.

  5. #5
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,846
    Rep Power
    19

    Default Re: Some Help with Static variables and methods

    Put simply, classes are loaded (and initialised) usually when they are first accessed in the code.
    So the static initialisers in a class are run at that point.
    quad64bit has explained the rest.

Similar Threads

  1. Static variables and methods
    By sudharani in forum New To Java
    Replies: 5
    Last Post: 04-25-2011, 02:07 PM
  2. cofusion with static and ordinary variables and methods
    By sandeepsai39 in forum New To Java
    Replies: 7
    Last Post: 09-02-2010, 12:25 PM
  3. What are Instance variables and static variables?
    By sandeshforu in forum New To Java
    Replies: 3
    Last Post: 09-09-2009, 05:48 PM
  4. accessing instance variables from static methods
    By ravian in forum New To Java
    Replies: 7
    Last Post: 03-01-2009, 10:09 PM
  5. significance of static variables and methods
    By imran_khan in forum New To Java
    Replies: 4
    Last Post: 08-02-2007, 09:52 AM

Posting Permissions

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