Tuesday 30 July 2013

smart uses of STATIC in JAVA

// siddhu vydyabhushana // 3 comments
STATIC IN JAVA
  • Every class has two parts.One is variable and other one is method.The variables are called instance variables and methods are called instance methods.This is because every time the class is instantiated ,a new copy of each them is created .They are accessed with dot operator.
  • The modifier static is used to specify that a method is a class method.A class method is a method that is invoked without being bound to any specific object of the class.These are associated with itself not an individual objects.
For Example:

       public static void main(String args[])

which means,this method  as one that belong to the entire class and not a part of any object of the class.so interpreter uses this method before any object is created. 

Three uses of static 

1.if you declare static in before variable that variables gets memory once from the heap.
E.g


static example 1:
class inc
{
 int i=0;
void print()
{

   i++;
     System.out.println(i);
   
}

}
class staticvariable
{
 public static void main(String args[])
 {
inc a=new inc();
inc b=new inc();
inc c=new inc();
a.print();   
b.print();   
c.print();   
 }
  
}
Output:
After modifying using static

Using static variable:
class inc
{
static int i=0;
void print()
{

   i++;
     System.out.println(i);
   
}

}
class staticvariable
{
 public static void main(String args[])
 {
inc a=new inc();
inc b=new inc();
inc c=new inc();
a.print();   
b.print();   
c.print();   
 }
  
}
Output:

2. if you declare any class using static without creating instance automatically when class loads it will be executed.
for example if we take public static void main(String args[]).
before executing all classes in a particular class the main method will be executed first because of using static modifier.

3.Static block: it will executed before main method.
for Example:


Example of static block:
 
class staticBlock
{
static
{
System.out.println("Executing Before main method");
}
public static void main(String args[])
{
System.out.println("WELCOME TO JAVA TYRO");
}
}
Output:

3 comments: