• iconJava Online Training In Andhra Pradesh and Telangana
  • icon9010519704

Opening Hours :7AM to 9PM

Java Static


Static Keyword

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

Static Variable
if any variable preceded by static keyword is known as static variable.
Syntax:
static datatype variablename=value;

Example:
static int x=10;

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
}

}
}



Static Method
If any method preceded by static keyword is known as static method.
Syntax:
static returntype methodname(list of parameters/no parameters)
{
...
...
}

  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
}
}

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
}
}

Output:
10
20
20
10
20
20
20



Static Block
Static block is used to execute a program without using main method.
Syntax:
static
{
...
...
}

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).