Java static keyword
Java static keyword Java uses the static keyword for memory management. It can be used along with variables, methods, blocks, nested class. It is used to share the same variable method for the given class. Generally, the main method of a class is labelled as static. To create a member as static, precede its declaration with the keyword static. A static member can be accessed before any objects of its class are created and without reference to any object. When a method declared as static, it cannot call as non-static. Java uses the following members that can be static:
- Method (class methods)
- Variable (class variable)
- Block
- Nested class
public class Demo{ static void method1() { System.out.println("This is method1"); } public static void main(String[] args) { method1(); }}Output
This is method1Java static methods A method that does not act upon instance variable of the class is known as a static method. A static method is declared with a static keyword. The reason why the static method does not act upon instance variable because the JVM first execute the static method after that, it creates the object. Most used example of the static method is main() method. A static method belongs to the class; it does not belong to the object of the class. A static method can access static data member. It may change the value of static data member. It can be accessed before any object of the class is created. Example With the help of this example, we will understand the use of the static keyword. This is an example of a simple calculation.
Class Calc{ static int cube(inta){ return a*a*a; } public static void main(String args[]){ int result=Calc.cube(7); System.out.println(result); } }Output
343Restrictions for static methods A static method has the following restrictions
- These methods can only directly call other static methods.
- These methods can only directly access static data.
- These methods cannot refer to this or super in any way
public class Demo1 { static int x=20; // static variable int y=40; //instance variable static void method1() // static method { x=40; System.out.println("This is method1"); y=20; // here it cannot make reference of a static variable method2(); //cannot make static reference to the non static method System.out.println(super.a); // cannot use super } void method2() { System.out.println("This is method2"); } public static void main(String[] args) { }}Why java main() is static? It is necessary for a java program because the JVM calls main() method before any objects are created. So, objects are not required to call a static method. If main() is a non-static method, then JVM will create an object first, then it will call the main(). It may generate ambiguity and will lead to the problem of extra memory allocation. Java static variable Any variable declared as static is known as a static variable. A static variable is referred to the common property of all objects like company name of the employees, college name of students, etc. it gets memory only once in the class area at class loading time.
- A static variable can be created at class level only.
- Static variable and block are executed in the order they are given in the program
- A static variable is used for fulfilling a common requirement.
- Static variable allocates memory only once in a class.
- Static variable makes the program memory efficient.
Public static variableName;Example-
public class CompanyData { int id; String name; static String Comp_name="AAA pvt.ltd"; public static void main(String args[]) { CompanyData c1=new CompanyData(); c1.id=100; c1.name=" akash shakya "; System.out.print(c1.id); System.out.print(c1.name); System.out.println(CompanyData.Comp_name); CompanyData c2=new CompanyData(); c2.id=200; c2.name=" Amritanshu shekhar "; System.out.print(c2.id); System.out.print(c2.name); System.out.print(CompanyData.Comp_name); }}Output-
100 akash shakya AAA pvt.ltd 200 Amritanshu shekhar AAA pvt.ltdWhen to Use the static variables and methods? A static variable is used for common property of all objects. Example- in a company all the employee have the same company name. The static method is used for changing static variables. Let’s understand this scenario with below example.
Program public class CompanyData1 { String name; int id; // static variable static String CompName; // static counter to set unique roll no static int counter = 0; public CompanyData1(String name) { this.name = name; this.id = setId(); } static int setId() { counter++; return counter; } static void setComp(String name){ CompName = name ; } void getEmployeeInfo(){ System.out.println("name : " + this.name); System.out.println("id : " + this.id); System.out.println("compName : " + CompName); } public static void main(String[] args) { CompanyData1.setComp("AAA pvt.ltd"); CompanyData1 c1 = new CompanyData1("Alok"); CompanyData1 c2 = new CompanyData1("Bablu"); c1.getEmployeeInfo(); c2.getEmployeeInfo(); } }output:
name : Alok id : 1 compName : AAA pvt.ltd name : Bablu id : 2 compName : AAA pvt.ltdJava static block Static block initializes the static variables. The block is executed at the time of class loading in memory. A class can have more than one static block, and they execute in the same sequence as they are written in the program. JVM executes it before the main(). Till JDK 1.6 it is possible to execute a Java program by static block without main(), but after 1.6, earlier version does not support this feature. Example
class Demo2 { static { System.out.println(" This is static block "); } public static void main(String args[]) { System.out.println("This is main function");}}Output
This is static block This is main functionMultiple static blocks As we have discussed before, a java program can have more than one static block. They will execute in the order as they are given in the program. Example for Java multiple blocks is
public class Demo3 { static { System.out.println("In static block1"); } static { System.out.println("In static block3"); } static { System.out.println("In static block2"); } public static void main(String args[]) { System.out.println("In main"); } }Output
In static block1 In static block3 In static block2 In mainStatic Nested class in Java (Static class)- The top-level class cannot be declared with a static modifier, but nested classes can be declared as static. Such classes are called static class or nested static class. In Java, we cannot make a top-level class as static but can simulate a static class like following steps-
- Declare the class as final, it prevents extension of the class.
- Make a constructor private, it prevents instantiation by client code.
- Make all the functions and members of the class as static.
public class OuterDemo { static int n=50; static class inner{ void msg() { System.out.println("Number is "+n); } public static void main(String[] args) { OuterDemo.inner obj=new OuterDemo.inner(); obj.msg(); }}}Output
Number is 50