Wednesday 23 December 2015

Java Static

Static can be used along with Variables, Methods, Class name and block.

Java Static Variables

  • Java instance variables are given separate memory for storage. If there is a need for a variable to be common to all the objects of a single java class, then the static modifier should be used in the variable declaration.
  • Any java object that belongs to that class can modify its static variables.
  • Also, an instance is not a must to modify the static variable and it can be accessed using the java class directly.
  • Static variables can be accessed by java instance methods also.
  • When the value of a constant is known at compile time it is declared ‘final’ using the ‘static’ keyword
  • Unlike non-static variables, such variables can be accessed directly in static and non-static methods.

Example:

//Program of static variable  
  
Class  Department {   
   int deptNo;  
   String empName;  
   static String orgName="ABC";  

     Department (int deptNumber,String eName){     
       deptNo= deptNumber;
       empName=eName; 
     }  
 void display (){
   System.out.println("DeptNo:"+deptNo+"\t EmpName:"+empName+"\t    OrgName:"+orgName);
}  
  
 public static void main(String args[]){  
 Department s1 = new Department (111,"Karan");  
 Department s2 = new Department (222,"Aryan");    
 s1.display();  
 s2.display();  
 }  


OutPut:


DeptNo:111    EmpName:Karan        OrgName:ABC
DeptNo:222    EmpName:Aryan        OrgName:ABC




Advantage of static variable:

It makes your program memory efficient (i.e it saves memory).


Java Static Methods: 


  •         Similar to static variables, java static methods are also common to classes and not tied to a java instance.
  •         Good practice in java is that, static methods should be invoked with using the class name though it can be invoked using an object. ClassName.methodName(arguments) or objectName.methodName(arguments)
  •          General use for java static methods is to access static fields.
  •          Static methods can be accessed by java instance methods.
  •          Java static methods cannot access instance variables or instance methods directly.
  •          Java static methods cannot use the ‘this’ & 'Super' keyword.
  •          Static methods can be accessed directly in static and non-static methods.
  •          The static method cannot use non static data member or call non-static method directly.

Example:


class StaticMethod{
  static int i;
  static String s;
  //Static method
  static void display()
  {
     //Its a Static method
     StaticMethod obj1=new StaticMethod();
     System.out.println("i:"+obj1.i);
     System.out.println("i:"+obj1.i);
  }

  void funcn()
  {
      //Static method called in non-static method
      display();
  }
  public static void main(String args[]) //Its a Static Method
  {
      //Static method called in another static method
      display();
   }
}


OutPut:

i:0
i:0


Q. why java main method is static?
Ans. because object is not required to call static method if it were non-static method, jvm create object first then call main() method that will lead the problem of extra memory allocation.



Java Static Classes 

  • A Class can be made static only if it is a nested Class. The nested static class can be accessed without having an object of outer class.
  • For java a static inner class it does not mean that, all their members are static. These are called nested static classes in java.


Example:


class StaticClass{

  //Static class
  static class X{
      static String str="Inside Class X";
  }

  public static void main(String args[])
  {
      X.str="Inside Class StaticClass ";
      System.out.println("String stored in str is- "+ X.str);
  }
}

OutPut:


String stored in str is- Inside Class StaticClass



Static Block 


  • Static block is mostly used for initialize the static variables. This block gets executed when the class is loaded in the memory.
  • A class can have multiple Static blocks, which will execute in the same sequence in which they have been written into the program.
  • It is executed before main method at the time of classloading.



Example:


class StaticBlock{ 
  static{
   System.out.println("static block is invoked");
  public static void main(String args[]){ 
   System.out.println("Hello main"); 
  } 

OutPut:


static block is invoked
       Hello main


 Q. Can we execute a program without main() method?

Ans. Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.

Eg: 
class StaticBlock{ 
  static{ 
  System.out.println("static block is invoked"); 
  System.exit(0); 
  } 

Output:

 static block is invoked (if not JDK7)

In JDK7 and above, output will be:

Output:

Error: Main method not found in class StaticBlock, please define the main method as:
public static void main(String[] args)

No comments:

Post a Comment

Java Packages Interview Question & Answers

All Packages Q) Thread Class Methods: - getName() run() getPriority() Sleep() isA...