Pages

Tuesday 16 October 2012

Static method and Static variable

Static method -

1)Static methods can be called by its class name instead of calling by reference.
2)A class containing only Static methods not required to be instantiated hence such class can be used for reusablity.
3)Inside a Static method - non static members cant be accessed but can declare non static references.
4)Static members will load at the time of loading a class and only once in the entire application.

public class Staticexample
{
private int i;

public static void main(String args[])
  {
System.out.println(i);// Error - "i" is a non static
  }

}



Static variable
1)it is one value per Class instead of one value per instance.
2)A class gets a single copy of a variable and all the instances of that class share the same copy.
3)All the static variables of a class are getting initialized before its object is getting created.
4)Default value will be assigned to static variable automatically based on the type if its not initialized explicitely.
5)Static variable should be accessed by a class name for the best usage of static rule.

public class StaticVariable
{

static int x=0;
}

public class StaticVariableUsage
{

public static void main(String args[])
  {
System.out.println(StaticVariable.x);
  }
}

Quiz

is it static variables are loaded first or static methods are getting loaded first ?


whtas the o/p
1)public class A{
static int i;
public void print(){
System.out.println(i);
}
}


2)public class B{
int i;
public static void go(){
System.out.println(i);
}
}