Learn static keyword in java

Welcome to flower brackets blog. Today we will learn static keyword in java.

In java, static keyword belongs to class. Whenever you declare a member (variable/method/nested class) as static, the static member belongs to class not object.

Syntax:

// declaring static variable
static String name;

// declaring static method
public static void methodName()
{
   // statements
}

public class Student 
{
   String name;
   static String school = "Delhi Public School";
}
// school name will be same for all students
Student obj1 = new Student();
Student obj2 = new Student();

That is, members (variable/method) can be accessed before its objects are created or without any reference.

Also read – learn nested classes in java

Static method can access static data member and can change the value of it. Meanwhile static variable makes java program memory efficient by allocating memory only once at the time of class loading.


Static variable in java

We can declare static variable by adding keyword “static” before variable name. Static variables are intrinsically global variables. Static variables are shared at class level only.

public class Employee 
{
   int empID;
   int empSalary;
   static String company;
   public void print()
   {
      System.out.println(empID + " - " + company);
   }
}

In class Employee we have declared static string variable “company” and we access the same in main method like this,

public class StaticExample
{
   public static void main(String[] args)
   {
      Employee emp1 = new Employee();
      emp1.empID = 8;
      emp1.empSalary = 40000;
      Employee.company = "IBM";

      Employee emp2 = new Employee();
      emp2.empID = 9;
      emp2.empSalary = 45000;
      Employee.company = "IBM";
      emp1.print();
      emp2.print();
   }
}

If you change a variable to static it will be applicable to (all) both objects and the objects share the same value.


Static method in java

We can declare a method as static by adding keyword “static” before method name. Static methods are accessed without creating object.

Static methods can call other static methods and access static data directly.

NOTE

Static methods cannot indicate super and this keywords.

public class Welcome 
{
   public static String Greetings(String message)
   {
      return message;
   }
 
   public String GreetWithSmile(String message)
   {
      return message;
   }
}

public class StaticExample 
{
   public static void main(String[] args) 
   {
      Welcome wc = new Welcome();
      Welcome.Greetings("Welcome to Flower Brackets!!");
      wc.GreetWithSmile("Hi!! Flower Brackets.");
   }
}

Here I have a class “Welcome” which has two methods. One is a static method and other is a non static method.

Static method means which contains “static” keyword in it. This method is not doing much. It’s just taking a string as an argument and it’s returning string.

Also read – switch statement java

And another method which is “GreetWithSmile” and this does not have any static keyword in it.

The static member only belongs to class not to the instance. So it will not belong to the instance of a class. So if you do something like this,

wc.Greetings("Welcome to Flower Brackets!!");

For Greetings method which is a static method we want to pass some message, say, “Welcome to Flower Brackets!!”. It will work. But it will give some warning like this,

Learn Static Keyword In Java

And the warning is “The static method Greetings from the type Welcome should be accessed in a static way”. So you cannot access “Greetings” method which is declared as static method.

You can access “Greetings” method directly from a class like this,

Welcome.Greetings("Welcome to Flower Brackets!!");

But when you try to access non static method ,

Learn Static Keyword In Java

“GreetWithSmile” method is not available in Welcome class or cannot be accessed directly with the class name.

“Greetings” method is accessed from the class and “GreetWithSmile” method which is not a static method cannot be accessed directly by class “Welcome”.

You can see (in the above image) there is no “GreetWithSmile” method. But non static method is available through the instance of a class.

Basically non static methods are available or can be accessed using object and static method should be accessed using the class itself not the instance.

Below is the correct way of using non-static method,

wc.GreetWithSmile("Hi!! Flower Brackets.");


When static block is called in java?

Static block is called as soon as class is loaded into JVM. It is also known as Static initialization block. For 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 we know the first method which is executed by JVM is main method. So it should first print “In main method”. But static block gets called when the class is loaded.

That means it will call before main method. As you can see the output “In static method” prints first. So static block always get executed first and then main method.

Next comes the question that can we have multiple static blocks in java? Yes. Using multiple catch blocks in java.


Multiple static blocks

What if I create one more static block in the above example. In java we can create more than one static block. For example,

public class Employee 
{
   int empID;
   int empSalary;
   static String company;
   static
   {
      System.out.println("static block");
   }
   public Employee()
   {
      System.out.println("Employee constructor");
   }
}

public class StaticExample
{
   public static void main(String[] args)
   {
      Employee emp1 = new Employee();      
      Employee emp2 = new Employee();      
   }
}

After running above java program,

Output:

static block

Employee constructor

Employee constructor

Constructor gets executed when you create an object and static block will be executed when you load a class. No matter how many objects a class have, the class will load only once.


What is the use of static?

The actual use is, for example,

public class StaticBlockExample
{
   static String name = "";
   static
   {
      name = "Kevin Peterson";
   }
   public static void main(String args[])
   {
      System.out.println("Name : " + name);
   }
}

In the above java program we have static variable String name. Initial value for this static variable is blank. We don’t have any value here.

In the main method I’m printing string name. If I print static string “name” the output would be ofcourse blank. Because the value of static string “name” is blank.

We assign a value to string “name” using static block. We cannot use constructors here. Because constructors only works on instance variables.

Moreover this is static variable. In order to initialize static variable we use static block. Now the output will be “Name = Kevin Peterson”.

So this is the way to use static block in java. Remember “static block always gets called when the class is loaded into JVM before main method”.


Java static nested class

Static nested class is a class created inside outer class. This class is declared with keyword static. Nested static class don’t need instance of outer class or nested static class to access its members.

class Outer
{
   static class Inner
   {
      // code goes here
   }
}

// Creating instance of static nested class

Outer.Inner obj = new Outer.Inner();

We can directly access static members and variables without creating object. In case, if we want to create instance of nested static class we don’t need to create instance of outer class.

Static nested class can access all static members of outer class. Also it can have all levels of access, that is, default protected, public except private.

It can be abstract or final. Last but not the least it can extend other classes and implement interfaces.

public class Outer 
{
   private int var = 100;
   private static int staticVar = 500;

   public void print()
   {
      System.out.println("outer method");
   }
   public static void outerPrint()
   {
      System.out.println("static outer method");
   }
   static class InnerNested
   {
      int innerVar = 10;
      public void innerPrint()
      {
         System.out.println("inner print method");
         System.out.println(innerVar);
         System.out.println(staticVar);
         outerPrint();
      }
   }
}

public class NestedStaticDemo 
{
   public static void main(String[] args) 
   {
      Outer.InnerNested nest = new Outer.InnerNested();
      nest.innerPrint();
   }
}

Output:

inner print method
10
500
static outer method

Related Posts