The static keyword is used in java mainly for memory management. It is used with variables, methods, blocks . It is a keyword that is used for share the same variable or method of a given class.
1) Java static variable
If you declare any variable as static, it is known static variable. The static variable can be used to refer the common property of all objects The static variable gets memory only once in class area at the time of class loading.
public class S1{ int id; String name; static String org =”NIELIT”; S1(int i,String n){ id = i; name = n; } void display () { System.out.println(id+” “+name+” “+org);} public static void main(String args[]){ S1 e1 = new S1(256,”James”); S1 e2 = new S1(257,”Dennis”); e1.display(); e2.display(); } } 2) Java static method Static method in Java is a method which belongs to the class and not to the object.
A static method can access only static data.
It is a method which belongs to the class and not to the object(instance)
A static method can access only static data. It can not access non-static data(instance variables).
A static method can call only other static methods and can not call a nonstatic method from it.
A static method can be accessed directly by the class name and doesn’t need any object
A static method cannot refer to “this” or “super” keywords in any way.
class ST { void multiply(int a, int b){ System.out.println(a*b); } static void add(int a, int b){ System.out.println(a+b); } } public static void main( String[] args ) { ST st = new ST(); st.multiply(2,6); add(5,9); } }
3)Java static block
Static blocks are also called Static initialization blocks. A static initialization block is a normal block of code enclosed in braces, { }Is used to initialize the static data member. It is executed before the main method at the time of classloading.
class s1{ static { System.out.println(“static block is called”); } public static void main(String args[]){ System.out.println(“main block”); } }