Static keyword in java

Let’s learn static keyword in java.

Static keyword in java

static keyword in java

In java a variable, block, method and nested class declared with keyword “static” can be accessed without creating object and before any object of the same class.

NOTE: ‘static’ keyword is one of the non-access modifier.

In the below java program we are accessing static method display() of class ‘Demo’ without creating object of class ‘Demo’ and before instantiating class ‘Demo’.

Static java example:

class Demo
{
   // static method 
   static void display() 
   { 
      System.out.println("in static method"); 
   }
}

public class StaticKeywordDemo 
{
   public static void main(String[] args) 
   {
      Demo.display();
   }
}



Output:

in static method


static class in java

Basically we cannot create top level static class in java. Instead we can only nest static class (inner class) inside an outer non-static class.

NOTE: static class helps in grouping classes.

Now let’s see an example,

public class Car
{
   public static class Engine
   {
      // static class Engine constructor
      public Engine()
      {
         System.out.println("Engine started");
      }
   }

   // Car class constructor
   public Car()
   {
      System.out.println("car is moving");
   }
}

public class StaticClassExample
{
   public static void main(String[] args) 
   {
      Car obj = new Car();
   }
}



Output:

car is moving

Let’s instantiate static class Engine. To do that we have to create object from static class Engine like this,

public class Car
{
   public static class Engine
   {
      // static class Engine constructor
      public Engine()
      {
         System.out.println("Engine started");
      }
   }

   // Car class constructor
   public Car()
   {
      System.out.println("car is moving");
   }
}

public class StaticClassExample 
{
   public static void main(String[] args) 
   {
      Car.Engine obj = new Car.Engine();
   }
}



Output:

Engine started

In the above example we accessed static inner class ‘Engine’ through outer class ‘Car’. By this we can understand static classes are seperate classes.

Also read – nested classes in java

But here static classes can access static methods and members of its enclosing class.

Now let’s learn to access static outer class members from static inner class. Here’s the example,

public class Car
{
   private static int engineNumber = 1191126;
   public static class Engine
   {
      // static class Engine constructor
      public Engine()
      {
         System.out.println("engine number is: " + engineNumber);
      }
   }

   // Car class constructor
   public Car()
   {
      System.out.println("car is moving");
   }
}

public class StaticClassExample 
{
   public static void main(String[] args) 
   {
      Car.Engine obj = new Car.Engine();
   }
}



Output:

engine number is: 1191126


static variable in java

To declare static variable in java, keyword “static” is used before variable name.

Syntax:

static datatype variableName;

Static variables are intrinsically global variables and shared amidst all objects of that class and it is class level variable.

Also read – this keyword in java

At the time of class loading static variables allocate memory only once. Hence saving memory. Let’s see how to declare static variable in java,

NOTE: 

  1. static variables are memory efficient used for memory management.
  2. static variable belongs to class. It can be accessed using class name.
  3. static variable is a class level variable and it is initialized when class is loaded.
  4. default values for non-static varaible and static variable are same. (int, short long: 0, float and double: 0.0, boolean: false, object reference: null).

Let’s see static variable example in java,

public class StaticVariableJava 
{
   static int empID;
   static String empName;
   // static method
   static void printDetails()
   {
      System.out.println("Employee ID: " + empID);
      System.out.println("Employee name: " + empName);
   }

   public static void main(String[] args) 
   {
      empID = 598886;
      empName = "Virat";
      printDetails();
   }
}



Output:

Employee ID: 598886
Employee name: Virat


static method in java with example

We can declare a method as static by adding keyword “static” before method name.

Static methods belongs to class and are accessed without creating object or instance of a class. For example, “main()” method.

Also read – switch statement java

Static methods can call other static methods and access static data directly. Now let’ see how to create a static method in java,

NOTE:

  • super and this cannot be used in static.
  • static method can change static data member value and static method cannot use non-static method or non-static members.

Let’s see static method java example,

class EmployeeDetail 
{
   int empNumber; 
   String empName; 
   static String company = "IBM"; 
   // static method
   static void change()
   { 
      company = "Infosys"; 
   } 
   // constructor to initialize variable 
   EmployeeDetail(int empNo, String name)
   { 
      empNumber = empNo; 
      empName = name; 
   } 
   // printing values 
   void print()
   {
      System.out.println(empNumber + " " + empName + " " + company);
   }
}


public class StaticMethodExample 
{
   public static void main(String[] args) 
   {
      // calling print() method
      EmployeeDetail.print(); 
      // create objects 
      EmployeeDetail obj1 = new EmployeeDetail(659, "Sachin"); 
      EmployeeDetail obj2 = new EmployeeDetail(660, "Virat"); 
      EmployeeDetail obj3 = new EmployeeDetail(661, "Dhoni"); 
      // calling print method 
      obj1.print(); 
      obj2.print(); 
      obj3.print();
   }
}



Output:

659 Sachin Infosys
660 Virat Infosys
661 Dhoni Infosys


Static block in java

Static block is used to initialize “static” data member of a class. Static block is executed before “main()” method.

It is also known as Static initialization block and it is executed only once. Here’s an example,

public class StaticBlockExample
{
   static
   {
      System.out.println("In static block");
   }
   public static void main(String args[])
   {
      System.out.println("In main method");
   }
}



Output:

In static block

In main method

As you can see the output “In static block” prints first. So static block always get executed first and then “main()” method.


When to use static variables and static methods in java?

As discussed earlier static variables are constant, that is, general to all objects and static methods are used to change static variables.

class Employee 
{
   String name; 
   int empNo; 

   // static variable 
   static String companyName; 

   // static number for unique employee number 
   static int number = 0;

   public Employee(String name) 
   { 
      this.name = name; 
      this.empNo = setEmpNo(); 
   }

   static int setEmpNo() 
   { 
      number++; 
      return number; 
   } 

   // static method 
   static void setCompany(String name)
   { 
      companyName = name ; 
   }

   // instance method 
   void getEmployeeInfo()
   { 
      System.out.println("Name : " + this.name); 
      System.out.println("Employee no : " + this.empNo); 
      // accessing static variable 
      System.out.println("Company name : " + companyName); 
   }
}

public class StaticDemo
{
   public static void main(String[] args) 
   {
      Employee.setCompany("IBM");
      Employee emp1 = new Employee("Sachin"); 
      Employee emp2 = new Employee("Virat");
      emp1.getEmployeeInfo(); 
      emp2.getEmployeeInfo();
   }
}



Output:

Name : Sachin
Employee no : 1
Company name : IBM
Name : Virat
Employee no : 2
Company name : IBM


Why is java main method static?

“main” method is static because there is no need of object creation. Java virtual machine calls it without creating instance.