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

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 263
    Comment on it

    Static Keyword

    Static keyword can be applied on

    1.Method

    2.Variable

    3.Class nested within another Class

    4.Initialization Block

    Static keyword can not be applied to

    1.Class (Not Nested)

    2.Constructor

    3.Interface

    4.Method Local Inner Class(Difference then nested class)

    5.Inner Class methods

    6.Instance Variables

    7.Local Variables

    Static method and variable belong to a class.

    To Invoke

    Using below example we will learn to access Static method and Static Variable.

    public class JavaStaticExample {
    
    static int i = 10;
    
    static void method() {
    System.out.println("Inside Static method");
    }
    
    public static void main(String[] args) {
    
    // Accessing Static method
    JavaStaticExample.method();
    
    // Accessing Static Variable
    System.out.println(JavaStaticExample.i);
    
    /*
    * No Instance is required to access Static Variable or Method as we
    * have seen above. Still we can access the same static variable and
    * static method using Instace references as below.
    */
    JavaStaticExample obj1 = new JavaStaticExample();
    JavaStaticExample obj2 = new JavaStaticExample();
    
    /*
    * Accessing static variable in Non Static way. Compiler will warn you
    * with below warning.
    *
    * The static field JavaStaticExample.i should be accessed in a static
    * way.
    */
    System.out.println(obj1.i);
    // Accessing satic method using reference.
    // Warning by compiler
    // "The static method method() from the type JavaStaticExample should be accessed in a static way"
    obj1.method();
    }
    }
    

 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: