Static Keyword Simplified in Java

0
21
Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share


Normally we create an object of the class using the new operator and access the methods and variables. Each instance of a class has its own copy of any member variables and methods.It is also possible to create member variables and methods that belongs to the class independent of any object of that class.So 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. We can call that method if no instance of the class has been created. In both the scenario we can achieve using static keyword.

A class contains two sections
1. Variable declaration(instance variables)
2. Method declaration(instance methods).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.These are common to all instances of a class. 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 elements gets executed only once at the beginning of the program.
Java libraries contain a huge set of static members.
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.They 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 {

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

LEAVE A REPLY

Please enter your comment!
Please enter your name here