Java

Static Class, Block, Methods And Variables In Java

The keyword “static” may be used to classes, variables, methods, and blocks. Static members may be accessed without an object since they are members of the class rather than a particular instance. To further grasp this, let’s look at an example:

We have a static method here. MyMethod() may be called without an object since a member becomes class level when it is made static. If we change it from static to non-static, then we must construct an object of the class before calling it.

class SimpleStaticExample
{
    // This is a static method
    static void myMethod()
    {
        System.out.println("myMethod");
    }
 
    public static void main(String[] args)
    {
          /* You can see that we are calling this
           * method without creating any object. 
           */
           myMethod();
    }
}

Output:

myMethod

Static Block

The static variables are initialized using the static block. When a class is loaded into memory, this block is performed. Multiple Static blocks may be included in a class, and they will all run in the order in which they were entered into the program.

Example 1: Single static block

As you can see, we initialized both of the static variables before accessing them in the main function.

class JavaExample{
   static int num;
   static String mystr;
   static{
      num = 97;
      mystr = "Static keyword in Java";
   }
   public static void main(String args[])
   {
      System.out.println("Value of num: "+num);
      System.out.println("Value of mystr: "+mystr);
   }
}

Output:

Value of num: 97
Value of mystr: Static keyword in Java

Example 2: Multiple Static blocks

Let’s see how Java handles numerous static blocks. The first static block runs before the second static block because they run in the specified sequence. Values initialized by the first block are therefore overridden by the second block.

class JavaExample2{
   static int num;
   static String mystr;
   //First Static block
   static{
      System.out.println("Static Block 1");
      num = 68;
      mystr = "Block1";
  } 
  //Second static block
  static{
      System.out.println("Static Block 2");
      num = 98;
      mystr = "Block2";
  }
  public static void main(String args[])
  {
      System.out.println("Value of num: "+num);
      System.out.println("Value of mystr: "+mystr);
   }
}

Output:

Static Block 1
Static Block 2
Value of num: 98
Value of mystr: Block2

Java Static Variables

Since a static variable is a class level variable, it is shared by all instances (or objects) of the class. In other words, you might argue that all instances of the class share a single copy of a static variable that is generated. Such variables only get a single memory allocation when the class is loaded into memory.
Several Vital Points:

  • Class Variables are another name for static variables.
  • These variables, in contrast to non-static variables, may be accessed directly in both static and non-static methods.

Example 1: Static variables can be accessed directly in Static method

Here, two static variables, var1 and var2, and a static method, disp(), are present. In the static approach, both variables are immediately accessible.

class JavaExample3{
  static int var1;
  static String var2;
  //This is a Static Method
  static void disp(){
      System.out.println("Var1 is: "+var1);
      System.out.println("Var2 is: "+var2);
  }
  public static void main(String args[]) 
  {
      disp();
  }
}

Output:

Var1 is: 0
Var2 is: null

Example 2: Static variables are shared among all the instances of class

In this example, the integer variable is static but the string variable is non-static. The result shows that although the non-static variables for the two objects are distinct, the static variable is shared by both, which explains why changes made to the static variable by object ob2 are reflected in both objects.

class JavaExample{
   //Static integer variable
   static int var1=77; 
   //non-static string variable
   String var2;

   public static void main(String args[])
   {
	JavaExample ob1 = new JavaExample();
	JavaExample ob2 = new JavaExample();
	/* static variables can be accessed directly without
	 * any instances. Just to demonstrate that static variables
	 * are shared, I am accessing them using objects so that 
	 * we can check that the changes made to static variables
	 * by one object, reflects when we access them using other
	 * objects
	 */
        //Assigning the value to static variable using object ob1
	ob1.var1=88;
	ob1.var2="I'm Object1";
        /* This will overwrite the value of var1 because var1 has a single 
         * copy shared among both the objects.
         */
        ob2.var1=99;
	ob2.var2="I'm Object2";
	System.out.println("ob1 integer:"+ob1.var1);
	System.out.println("ob1 String:"+ob1.var2);
	System.out.println("ob2 integer:"+ob2.var1);
	System.out.println("ob2 STring:"+ob2.var2);
   }
}

Output:

ob1 integer:99
ob1 String:I'm Object1
ob2 integer:99
ob2 STring:I'm Object2

Static Class

Only nested classes are capable of having their members turned static.

Nested static classes do not need an outside class reference.
The non-static members of the outer class cannot be accessed by a static class.
We’ll observe these two points with the aid of the following illustration:

Static class Example

class JavaExample{
  private static String str = "BeginnersBook";

  //Static class
  static class MyNestedClass{
    //non-static method
    public void disp() {

      /* If you make the str variable of outer class
       * non-static then you will get compilation error
       * because: a nested static class cannot access non-
       * static members of the outer class.
       */
      System.out.println(str);
    }

  }
  public static void main(String args[])
  {
    /* To create instance of nested class we didn't need the outer
     * class instance but for a regular nested class you would need
     * to create an instance of outer class first
     */
    JavaExample.MyNestedClass obj = new JavaExample.MyNestedClass();
    obj.disp();
  }
}

Output:

BeginnersBook

Related Articles

Leave a Reply

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

Back to top button