Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Static in Java

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 311
    Comment on it

    One of the most important topic that we encounter in java. We can use static with class name, methods name, variables name and block. Static keyword mainly used for memory management.

    1. Static variable
    2. Static variable takes memory only once when the class is loading. We use static variable to represent common behavior of all objects.

      Sometimes in a class we need some variable that would be same all the time, and then should declare them as static.
      Advantage is we can save memory.

      Example:

      class Employee { 
      int empId; 
      String empName; 
      static String companyName = ABC 
      } 

      In a situation, when we know the company name will be same for all employees them it should be static.

    3. Static method
    4. Static is related to the class not related to object means we dont need to create the object of a class.
      Static method use static variables and can modify the value of it.
      But the limitation is we cant use non static variables and cannot invoke non static method directly.
      We cannot use super and this as a context.

    5. Static block
    6. Static block is used when we want to execute something before the main method to execute. Example:
      Class StaticBlockExample{ 
      
      static{ 
      System.out.println(I am static .); 
      } 
      
      Public static void main(String args[]){ 
      StaticBlockExample sBE = new StaticBlockExample(); 
      System.out.println(I am Main); 

      } }

      I am static will be printed first.

    7. Static Class
    8. Static class concept use in nested class. Nested class can be static.
      Means when we want to access inner class without creating object of outer class.
      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.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: