Static Keyword Simplified in Java



Normally we create an object of the class using the new operator and access the methods and variables. But if we want to have one piece of storage for a particular piece of data, regardless of how many objects are created or even no objects are created. Or a method that is not associated with any particular object of a class. That method we can call if no instance of the class has been created. In both the scenario we can achieve using static keyword.

When we declare variables(s) or method(s) is/are static, it means that the data or method is not associated with any particular object instance of that class. Thus even if we never create an object of that class, we can still call them or access the piece of static data.

For a non-static data member or method, we need to create an object of the class as they belong to the particular object they are working with. Since static methods/variables don't need any objects to be created before they are used, they can not access non-static members and methods. This is because non-static members and methods first tied with an object.

To remember easily we can say anything with the static keyword (modifier) associated to it will be the property of the class but not the property of the object. Since there will one class and many objects are created from it, we can say the static keyword associated things are created only once and shared among the objects of that class. This is somewhat a global variable or global function concept. The meaning of static varies from context to context.  Static things load first while we execute any program.
Static keyword can be applied to
  • Class
  • Methods
  • Block
  • Variable
  • Import 
Static Class:
Java, in general, does not allow normal classes to be static but it allows any number of classes created inside a non-static class. They are called Nested Inner class. Nested Inner classes can be static in nature.
Static Methods:
static methods are those methods that belong to a class.T hey don't belong to the objects created from the class. It can access only static data but not any non-static data elements. A static method can call only a static method(s) but can not call any non-static methods. A static method can only be accessed directly without creating an object by using the <ClassName>.<MethodName()>. A static method can not refer to this or super keywords. So we can not call a non-static method from inside a static method. But we can call a static method from inside of a non-static method(by creating an instance of the class).

class myStaticTest{
 static int i=10;
 }
class staticIncrementTest{
public static void increment(){
        //Accessing a static variable from a static method by creating Object
 myStaticTest SI=new myStaticTest();
 SI.i++;
       //Accessing a static variable from a static method directly
 myStaticTest.i++;
}
}
 
The main method is a static method hence can be called without creating an object and before any other thing runs.
An example to call a static method from inside of a static method:


public class MyStaticTestDemo {
 static int sum(int x, int y) {
 return x + y;
 }
 public static void main(String[] args) {
  int ans = MyStaticTestDemo.sum(15, 13);
  System.out.println(ans);
 }
}
 
The output of the code: 28 In the above example if we remove the static modifier from sum subroutine, it will become non static method. In that case statioc main will try to access non static sum() method. This is not allowed in java.JVM will throw the below exception: Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot make a static reference to the non-static method sum(int, int) from the type MyStaticTestDemo at com.myDigitalVoice.MyStaticTestDemo.main(MyStaticTestDemo.java:8) An example to call a non static method from inside of a static method:


public class MyStaticTestDemo {
 int sum(int x, int y) {
 return x + y;
 }
 public static void main(String[] args) {
  MyStaticTestDemo mstd=new MyStaticTestDemo();
  int ans=mstd.sum(12,13);
  System.out.println(ans);
 }
}
 
Output of the code: 25

Static Block:
A block that is loaded and executed as soon as JVM loads a java class. Even this happens before the execution of the main method.
There is a popular question asked to write a code to print Hello World without main. The same can be done through this.

public class myDemo{
static{
System.out.println("Hello World");
system.exit(0);
}
}
 
We need to terminate the code as after this the JVM will look for the main method which is not present and gives an error message.
$javac myDemo.java
$java -Xmx128M -Xms16M myDemo
Error: Main method not found in class myDemo, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend JavaFX.application.Application

Static Variables:
Again static variables belong to the class and initialized at first during execution. A single copy of the static variable is shared by all instances of the class.A static variable can be accessed directly by using <ClassName>.<VariableName>

public Class myStaticTest{
static int i=10;
}
now if we write two lines of code:

myStaticTest t1=new myStaticTest();
myStaticTest t2=new myStaticTest();
 
at this point, t1.i and t2.i will share the same i and have the same value as 10.
There are two ways to access static data:

  1. by creating an object of that class like t1.i;
  2. directly through its class name like myStaticTest.i;
Remember that static variables are like normal variable and not constant hence we can do any operations on that variable like- t1.i=ti1.i+1; this will increase the i value by one and i becomes 11. Now all the places where this i is referred will get i=11

here is one example:

public class MyStaticTestDemo {

 public static void main(String[] args) {
  System.out.println(myStaticTest.i);
  staticIncrementTest.increment();
  System.out.println(myStaticTest.i);
 }
}
class myStaticTest{
 static int i=10;
 }
class staticIncrementTest{
public static void increment(){
 myStaticTest SI=new myStaticTest();
 SI.i++;
 myStaticTest.i++;
}
}
 
Output of the code: 10 12
It is often told that static methods are not proper object oriented design as they have the semantics of a global function.And with static methods we do not send message to the objects as there is no this keyword support.However they are pragmatic and useful.

Static Imports:
Import directives or statements provides us to refer to a class. like javax.swing.JPanel for JPanel. If we see the directive is little complex and compound in nature.Every time we need to mention in order to use them .To refer the a static members we need to mention package name and variable name like-Math.Sqrt or System.out.
static imports are little different thing than class,methods and variables. The purpose of the static import eliminates the need of the qualifying a static member with the class name. The static import is similar like normal import. We can use the import statement to import classes from packages and use them without providing the qualifying the package name. Similarly,we can use the static import statement to import static members from a class and use them without providing the fully qualified class name.
The syntax is as follows:
import static <packageName>.<subPackageName>.<className>.staticMemberName;
or
import static <packageName>.<subPackageName>.<className>.*;
Before introducing the static import feature,we had to use the static member with the fully qualifying class name.
It is introduced in java in Java 5.0.
Example:

double areaOfCircle=Math.PI*radious*radious
 
PI is the static member of the Math class.
We can use the static member in the code without providing fully qualified class name. or interface name.static import feature eliminates the redundancy of using the qualified class name with the static member  name and increase the readability of the code.
Use of a Class:

import static java.lang.Math.*;
public class MyMathOperations{
public void circle(double r){
double area=PI*r*r;
System.out.println("The area of the circle is"+area);
}
public static void main(String args[])
{
MyMathOperations mathOps=new MyMathOperations();
mathOps.circle(2.3);
}
} 
The output of the code:
$javac MyMathOperations.java
$java -Xmx128M -Xms16M MyMathOperations
The area of the circle is16.619025137490002
Use of a interface:

public interface Student_Grade
{
public static final double StudentsWithAGrade=.5;
public static final double StudentsWithBGrade=.25;
}

import static Student.Student_Deatils.Student_Grade;
Class StudentFinalGrade{
public static void main(String args[]){
double A_grade_Student=StudentsWithAGrade*StudentsWithCurrentGrade;
double B_grade_Student=StudentsWithBGrade*StudentsWithCurrentGrade;
}
}
Similarly if we import java.lang.System.out then we can directly use out.println() instead of System.out.println().
static import statements requires a (packageName) even for classes in the standard package like java.lang. So it is not possible to do a static import from a class which stays in the default package.
Static Keyword Simplified in Java Static Keyword Simplified in Java Reviewed by Animesh Chatterjee on September 12, 2018 Rating: 5

No comments:

Powered by Blogger.