static in java

 Static keyword:

    The static keyword used for memory allocation in java. We can apply static keyword for variables, methods, blocks and Nested class.
If Static keywords are executed before the main method and allocated memory at compile time only.

Variables:
These are class variable references and sample value for all methods.
Memory allocated only once at compile time only.
It is also known as class variables.
Ex: School name of students

Methods:
Static methods are allocated memory at compile time and execute before the main method.
These methods are also known as class methods.
The static methods are accessed by using the class name only, we can't access  by using the object.

Blocks:
These are executed before the main method.
These are used to initialize static data members.

Nested class (Inner class): 

For Nested class, we can use static keyword.
If a class declared as a static keyword it becomes a static class. Static classes can be accessed by outer class without an  object. We can't create an object for inner classes.

Advantage:
Static keyword saves memory.

Disadvantages:
This and super can't be used in static context.
Static methods cannot use non-static data members.

Java program:

class Sample{

 int hallticketNumber;
 String studentName;
 static String schoolName="Govt. High School";    //static variable

 Sample(int h,String n){
 hallticketNumber=h;
 studentName=n;
 }

 void display(){
 System.out.println(hallticketNumber+" "+studentName+" "+schoolName);
 }

 static{                                                                            //static block
 System.out.println("This is static block");
   }

 static class sample2 {                                                   //static class
 static String name="inside class";
 }
  static void dis(){                                                         //static method
            System.out.println("This is  static method");
              }

   public static void main(String []args){

 Sample.dis();
 System.out.println("student Details");
 Sample sa1=new Sample(1,"Ramu");
 Sample sa2= new Sample(2,"Raju");
 sa1.display();
 sa2.display();

   }

}

Why  main ( ) method static in java?
       It is a class method and first JVM create an object for class and call the main method.
It leads to a big problem for memory allocation so the main method is static.

What is the error occurs if the main() method is deleted in your class?
      The Java code is compiled successfully. At run time, It gives an error.

Interview Questions:

What is static in java?
How to access static methods in java?
What is class variable?
What is the class method?
What is the use of a static keyword in java?
Why is the main method static?
Why main( ) method is static in java?




EmoticonEmoticon