Tuesday , November 21 2017
Home / java / Java Static Variable Method Block Class Example

Java Static Variable Method Block Class Example

In the previous tutorials, we have seen about different types of Java variables such as instance, static  and local variables. If you haven’t seen that tutorial, it is recommended to see before moving further this.

This tutorials, lets you a deep understanding about Java Static keyword and how do we use in our day to day development environment.

Java Static:

In Java Static is a keyword, it is used to define a specific functionality (block of execution) at class level, hence the static functionality is the class level functionality.

Since the static is a keyword, we can use this in front of variables, methods, blocks and inner classes too.

Lets see these four usages of a static keyword in detail.

Static variables :

A variable which is declared by using the static keyword is called as a static variable. Static variables are consider to be class level variables, because the values of the static variables are at class level, and not bound to be a specific instance of that class, where as in instance variables the value of a variable is bound to be with a specific instance.

Example : public static int a;

Static variables are allocated memory in static pool, and it is happening while loading the class itself.

Since the static variable are class level variables, we don’t need any instance to access these variables. We can directly access the static variables by using the class name itself.

8 Important points about static variable:

  • static variables are also called as class variables.
  • Class variables that are belonging to the entire class, not a specific instance of the class.
  • static variables are declared with the static keyword.
  • A single static variable can be shared by all instances of a class.
  • We can’t access the static variables from the normal methods.
  • Class variables are allocated memory only once at the time of class loading. which can be commonly accessed by all the instances of the class.
  • Static variables are allocated memory the static pool.
  • Since memory for the class variables is allocated at the time of loading the class itself, we can access the static variables directly with the class name itself.

Static MemoryExample of Static Variables:


class SampleStaticClass {

    static int x;
}

public class StaticVariableDemo {

    public static void main(String[] args) {
        SampleStaticClass.x = 20;
        System.out.println("A.x -- " + SampleStaticClass.x);
        SampleStaticClass object = new SampleStaticClass();
        object.x = SampleStaticClass.x + 20;
        System.out.println("ob.x -- " + object.x);
        SampleStaticClass.x = object.x - 10;
        System.out.println("A.x -- " + SampleStaticClass.x);
        System.out.println("ob.x -- " + object.x);
        SampleStaticClass object2 = new SampleStaticClass();
        object2.x = (object2.x * 2) + (SampleStaticClass.x - 10 + object.x);
        System.out.println("A.x -- " + SampleStaticClass.x);
        System.out.println("ob.x -- " + object.x);
        System.out.println("ob1.x -- " + object2.x);

    }
}

SampleStaticClass.x — 20
object.x — 40
SampleStaticClass.x — 30
object.x — 30
SampleStaticClass.x — 110
object.x — 110
object2.x — 110

Default Values of Static Variables :

For static variables it is not required to perform initialization explicitly. The JVM will provide default values to it.

  • In the case of primitives, the default value is zero (0).
  • In the case of object and characters, the default value is ‘null
  • In the case of boolean, the default value is ‘false‘.

Static Methods:

If a method that declared by using the static keyword, then we can say that method is a static method. The extreme example for a static method in Java is main method.

Like static variables, static methods are also called without using the object. We can directly call the static methods from the main method, since the main method also a static method.

Point about static methods:

  • Static methods can be accessed directly by using class name.
  • Static methods can’t be overridden.
  • Non-static methods can access the static methods only by using the class name.
  • Static methods can also access the non-static methods by using the instance of the class.
  • Both static and non static methods are not accessed directly.
  • Static method cannot refer to “this” or “super” in any ware.

Example for static methods :


public class StaticMethodDemo {

    public static void main(String[] args) {
        someStaticMethod();
    }

    public static void someStaticMethod() {
        System.out.println("Hello I am a static method ");
        StaticMethodDemo methodDemo = new StaticMethodDemo();
        methodDemo.sample();
    }

    public void sample() {
        System.out.println("Normal Method ");
        StaticMethodDemo.someOtherStaticMethod();
    }

    public static void someOtherStaticMethod() {
        System.out.println("Hello I am some other static method ");
        StaticMethodDemo methodDemo = new StaticMethodDemo();
        methodDemo.sample();
    }

}

Static block:

We have different types of blocks in Java, like initialization block, synchronized block and static block. Every block can have it own usages. Here a static block is a block statements, which is defined by using the static key word.

static{

// Code Here

}

Like static variables and methods, static blocks are also class level. Hence the static blocks will be executed at the time of class loading. If we want to perform any operation while loading the class, we can define that functionality with in the static blocks.

Usages of static blocks:

  • registering the database drivers,
  • loading the native libraries.

We can define any number of static blocks in a class and all will be executed from the top to bottom.

Points about static Block:

  • Static blocks can be executed by the JVM.
  • We can not access the static blocks directly or indirectly.
  • We can not directly access the non static content from the static blocks.
  • Static blocks can executed before the default constructor. The priority of static block is high compared to default constructor.
  • We can’t change the access of static blocks (There are no public ,private ,protected static blocks).

Example of Static Blocks :


public class StaticBlockDemo {

    static {
        System.out.println("static Block 1");
    }

    public StaticBlockDemo() {
        System.out.println("In default Constructor");
    }

    static {
        System.out.println("static Block 2");
    }

    public static void main(String[] args) {
        StaticBlockDemo blockDemo = new StaticBlockDemo();
    }

    static {
        System.out.println("static Block 3");
    }

}

static Block 1
static Block 2
static Block 3
In default Constructor

One bonus answer for you guys ! regarding static keyword.

Can we write a Java program with out main method ?

Yes. We can write a program with out using the main method, but this is possible before versions of Java 1.7. In Java 1.7, JRE looks for a main method before going to load the class.If JRE doesn’t find the main it will throw the bellow error.


Main method not found in class StaticBlockDemo, please define the main method as:
public static void main(String[] args)

In before versions of Java 1.7 JRE looks for the main method after executing the static blocks. But the execution and priority of the static blocks are fixed.

Static Class :

In Java we can create a class as static by using the static keyword as variables, methods and blocks. But we have one extreme limitation while creating the static classes.

That is we can only create static classes with in the outer class. We can’t create an outer class as static class. Hence we can only make the class as static if and only if that is inner class.

What is inner class ?

A class defined under the another class is called inner class or nested class. An inner class may be static or non-static. A class is enclosed with the nested class is called as outer class.

There are some functional differences between the static inner class and non-static inner class.

static vs non-static inner classes :

  • static inner class doesn’t need a reference to access the outer class members, where as non-static inner class should have the reference of outer class to access the outer class members.
  • static inner class can only access the static member of outer class, where as non-static inner class can access both static and non-static members of outer class.

Example of static and non static inner classes :


public class InnerClassDemo {

public static void main(String[] args) {

// Accessing the Static Inner class
InnerClassDemo.StaticInnerClass innerClass = new StaticInnerClass();
System.out.println("StaticInnerClass value  : " + innerClass.getValue());

// Accesing the Normal Inner class
InnerClassDemo.NormalInnerCalss normalInnerCalss = new InnerClassDemo().new NormalInnerCalss();
System.out.println("normalInnerCalss Value : " + normalInnerCalss.getValue());

}

static class StaticInnerClass {

int a = 10;

public int getValue() {
return a;
}
}

class NormalInnerCalss {

int instVar = 20;

public int getValue() {

return instVar;
}
}

}

Output :

StaticInnerClass value  : 10
NormalInnerCalss Value : 20

 

About chandrashekhar

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Recommended

How to add dynamic files to JTree

In the previous tutorial, we learn about a simple JTree. This tutorial is for adding …

Leave a Reply

Your email address will not be published. Required fields are marked *