Java Tutorial
Static keyword can be applied with variables, methods, blocks and nested class.
A static method can be called without the need for creating an instance of a class. class name can be used to invoke the static variable and methods.
The static keyword in Java is used mainly for memory management.
The static variable can be used to refer the common property of all objects and it is not unique for each object.
Memory is allocated only once in class area at the time of class loading for static variables. It makes your program memory efficient (it saves memory).
class StaticExample { // memory is allocated only once and value is retained. static int count=10; // static block static { System.out.println("Static block is called first"); } // static nested class static class Inner { static void msg() { System.out.println("msg method is called from static Inner class"); } } //A static method belongs to the class rather than object of a class. //A static method can be called without the need for creating an instance of a class. //static method can access static data member and can change the value of it. static int add(int val1, int val2) { return val1+val2; } StaticExample() { count++; System.out.println(count); } int a=50; // non-static variable cannot be accessed by static method public static void main(String args[]) { System.out.println(StaticExample.count); // static variable is called StaticExample.Inner.msg(); int result= StaticExample.add(16, 16); // Static method is called System.out.println(result); // Instance variable cannot be accessible inside static method. //System.out.println(a); // Compile time error //this and super cannot be used in static context. StaticExample obj1=new StaticExample(); StaticExample obj2=new StaticExample(); } }Output:
Java Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page