Opening Hours :7AM to 9PM
Static is a keyword in java language which is used to allocates the sufficient memory space for the class (variables and methods).In java language these are classified into following types
1.Static Variable
2.Static Method
3.Static Block
class Demo { int x; // x is a instance variable static int y; // y is a class variable // here x,y are the Global variables void show(int z) // z is formal variable { int p; // p is a local variable if() { int q; // q is a block variable } } }
If any method preceded by static keyword is known as static method.
static returntype methodname(list of parameters/no parameters) { Statement 1; Statement 2; ... ... }
Method: 1. Static Method 2. Non Static Method a. Concrete Method (Normal Method) b. Abstract Method (Incomplete Method)(Inheritance)
class Demo { int x=10; //non static variable static int y=20; // static variable void show() { System.out.println(x); // You get output System.out.println(y); // You get output } static void disp() { //System.out.println(x); // You get error //because static mentods can not accept non static variables System.out.println(y); // You get output } } public class Main { public static void main(String args[]) { Demo d=new Demo(); d.show(); // You get output d.disp(); // You get output System.out.println(d.x); // You get output System.out.println(d.y); // You get output //Note: By using object we have to call all static and non static variables and methods //Demo.show(); You Get error Demo.disp(); // You get output //System.out.println(Demo.x); // You get error System.out.println(Demo.y); // You get output //Note: By using class we have to call static methods only } }
Static block is used to execute a program without using main method.
static { Statement 1; Statement 2; ... ... }
class Main { static { System.out.println("Welcome"); System.exit(0); } }Note:
It is not available in latest versions(It works only java 6 before versions).