Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

Java

Learn step by step



Static Keyword

The static keyword is used in java mainly for memory management. We may apply static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.

The static can be:

1. variable (also known as class variable)
2. method (also known as class method)
3. block
4. nested class

1. 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 (that is not unique for each object) e.g. company name of employees,college name of students etc.
  • The static variable gets memory only once in class area at the time of class loading.

Advantage And Disadvantage of static variable

Advantages: Static members/methods are used as in helper classes say like Math or in constants classes. which helps other objects to utilize Strings or useful functions for which you do not need to create object but invoked using Class name.
Example – singleton objects are invoked using a static function.

Disadvantages: Static members are part of class and thus remain in memory till application terminates and can’t be ever garbage collected. Using excess of static members sometime predicts that you fail to design your product and trying to cop of with static / procedural programming. It denotes that object oriented design is compromised. This can result in memory over flow.
Also there are certain disadvantages if you make any method static in Java for example you can not override any static method in Java so it makes testing harder you can not replace that method with mock. Since static method maintains global state they can create subtle bug in concurrent environment which is hard to detect and fix.

Example of static variable


public class StaticDemo {
// static variable - the same on all instances of a class

static int X = 10;
// non static variable
int Y = 5;
public static void main(String[] args) {
StaticDemo instance1 = new StaticDemo();
StaticDemo instance2 = new StaticDemo();
System.out.println("instance1.X = " + instance1.X + " instance1.Y = " + instance1.Y);
System.out.println("instance2.X = " + instance2.X + " instance2.Y = " + instance2.Y);
instance1.X = 15;
instance1.Y = 10;
System.out.println("After updating X value to 15 and Y value to 10 from intance1 :");
System.out.println("instance1.X = " + instance1.X + " instance1.Y = " + instance1.Y);
System.out.println("instance2.X = " + instance2.X + " instance2.Y = " + instance2.Y);
}
}

Output

instance1.X = 10 instance1.Y = 5
instance2.X = 10 instance2.Y = 5
After updating X value to 15 and Y value to 10 from intance1 :
instance1.X = 15 instance1.Y = 10
instance2.X = 15 instance2.Y = 5
Example of counter without static variable

In this example, we have created an instance variable named count which is incremented in the constructor. Since instance variable gets the memory at the time of object creation, each object will have the copy of the instance variable, if it is incremented, it won't reflect to other objects. So each objects will have the value 1 in the count variable.


class Counter{
int count=0;//will get memory when instance is created

Counter(){
count++;
System.out.println(count);
}

public static void main(String args[]){

Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();

}}

Output

1
1
1
Example of counter by static variable

As we have mentioned above, static variable will get the memory only once, if any object changes the value of the static variable, it will retain its value.


class Counter{
static int count=0;//will get memory only once and retain its value

Counter(){
count++;
System.out.println(count);
}

public static void main(String args[]){

Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();

}}

Output

1
2
3
2. Static Method

If you apply static keyword with any method, it is known as static method

  • A static method belongs to the class rather than object of a class.
  • A static method can be invoked 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 methods in Java can be called without creating an object of class. Have you noticed why we write static keyword when defining main it's because program execution begins from main and no object has been created yet. Consider the example below to improve your understanding of static methods.

Example of Java static method example program


class Languages {
public static void main(String[] args) {
display();
}

static void display() {
System.out.println("Java is my favorite programming language.");
}
}

Output

Java is my favorite programming language.

Example of Java static method vs instance method
Instance method requires an object of its class to be created before it can be called while static method doesn't require object creation.


class Difference {

public static void main(String[] args) {
display(); //calling without object
Difference t = new Difference();
t.show(); //calling using object
}

static void display() {
System.out.println("Programming is amazing.");
}

void show(){
System.out.println("Java is awesome.");
}
}

Output

Programming is amazing.
Java is awesome.

Example of Using static method of another classes
If you wish to call static method of another class then you have to write class name while calling static method as shown in example below.


mport java.lang.Math;

class Another {
public static void main(String[] args) {
int result;

result = Math.min(10, 20); //calling static method min by writing class name

System.out.println(result);
System.out.println(Math.max(100, 200));
}
}

Output

10
200
3. Static Block

Unlike C++, Java supports a special block, called static block (also called static clause) which can be used for static initializations of a class. This code inside static block is executed only once: the first time you make an object of that class or the first time you access a static member of that class (even if you never make an object of that class).

  • Is used to initialize the static data member.
  • It is executed before main method at the time of classloading.



// filename: Main.java
class Test {
static int i;
int j;

// start of static block
static {
i = 10;
System.out.println("static block called ");
}
// end of static block
}

class Main {
public static void main(String args[]) {

// Although we don't have an object of Test, static block is
// called because i is being accessed in following statement.
System.out.println(Test.i);
}
}

Output

static block called
10


class A{

static{System.out.println("static block is invoked");}

public static void main(String args[]){
System.out.println("Hello main");
}
}

Output

static block is invoked
Hello main

Also, static blocks are executed before constructors. For example, check output of following Java program.


// filename: Main.java
class Test {
static int i;
int j;
static {
i = 10;
System.out.println("static block called ");
}
Test(){
System.out.println("Constructor called");
}
}

class Main {
public static void main(String args[]) {

// Although we have two objects, static block is executed only once.
Test t1 = new Test();
Test t2 = new Test();
}
}

Output

static block called
Constructor called
Constructor called


Related Videos