Learn Static Keyword In Java

Welcome to flower brackets blog. Today we will learn static keyword in java. In this post we will see what does the static keyword do in a class.

In my previous posts you may have seen the usage of keyword “static” with some member method or member variables of a class and you maybe curious what is the meaning of this….

What is static in Java with example?

In java static keyword is non-access modifier. Whenever you declare a member (variable/method/nested class) as static the static member belongs to the class.

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

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

Syntax:

// declaring static variable
public static varName;

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

Let me give you an example,

public class StaticDemo 
{
   // declaring static method
   static void hello()
   {
      System.out.println("I'm static method!!");
   }
   public static void main(String[] args) 
   {
      // here we are calling hello() method without
      // creating object.
      hello();
   }
}

Output:

I’m static method!!

In java programming static keyword can be applied to blocks, methods, nested classes and variables. Let me explain all these terms one by one.


What is meant by static variable in java?

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

Here’s the java program on static variables,

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

As you can see the above java program we have declared a static variable “age” and we access static variable in main method like this,

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


What is meant by 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.");
   }
}

In the above java program I have a class called 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 Case Example In Java

We have another method. It has different name which is “GreetWithSmile” and this does not have any static keyword in it.

The static member only belongs to the 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!!");

Greetings which is a static method and we want to pass some message, say, “Welcome to Flower Brackets!!”.

It will work and it will work fine 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 Welcome class.

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 the nonstatic methods are available or can be accessed using the instance of a class and the 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.");


What is static block of code in Java?

Static block is a block which is executed when class is loaded into JVM. That is, before (public static void main) main method, static block is called.

If we write code/anything in static block it will execute this static block first then only it will move towards main method.

Let’s see a sample java program,

public class StaticBlockDemo 
{
   static int empNumber;
   static String empName;
   static
   {
      empNumber = 1004;
      empName = "Kevin Peterson";
   }

   public static void main(String[] args) 
   {
      System.out.println("Employee number : " + empNumber);
      System.out.println("Employee name : " + empName);
   }
}

Output:

Employee number : 1004
Employee name : Kevin Peterson

So we are not writing anything in this main method we are writing everything in this static. Static variable, static methods and static class belong to object.

They are common to all the objects because they are static.

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 MultipleStaticBlockExample
{
   static
   {
      System.out.println("First Static block");
   }
   public static void main(String args[])
   {
      System.out.println("In main method");
   }
   static
   {
      System.out.println("Second Static block");
   }
}

Now as per multiple static block concept it should first call all the static blocks in sequence and then it should go for main.

After running above java program,

Output:

First Static block

Second Static block

In main method

Of Course it’s printing in sequence (as you can see the output). That means if you have multiple static blocks it will always go in sequence. Because static blocks always get called when the class is loaded.

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


What is static nested class in Java?

Static nested class is a class created inside another class. This class is declared with static keyword. Like static method static nested class cannot access instance variable and instance methods of outer class.

class Outer
{
   static class Inner
   {
      // statements
   }
}

// Creating instance of static nested class

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

Static nested class uses object reference to access instance variable and instance methods of outer class. Static nested class can access static data members of outer class including private.

Let’s see static nested class example,

public class StaticNestedDemo 
{
   static int studentID = 10004;
   static class Inner
   {
      void print()
      {
         System.out.println("Student ID is : " + studentID);
      }
   }
   public static void main(String[] args) 
   {
      StaticNestedDemo.Inner obj = new StaticNestedDemo.Inner();
      obj.print();
   }
}

Output:

Student ID is : 10004

In the above java program we have created instance of nested static class because it has instance method print().

We have not created object of outer class, that is, StaticNestedDemo class. Because static nested class is static and static properties, static methods or static classes can be accessed without object.


Conclusion

That’s it guys. In this post we covered learn static keyword in java with example, static methods and static variables.

I hope you understood what is static keyword in java concept. You can subscribe to my blog flower brackets if you haven’t already.

Related Posts