Static keyword in Java Static is known as a non-access modifier.
Static keyword can be used to declare the following.
Variables : In easy terms, the static variable is the variable which is common for all the object of that particular class. It can be called with or without object instance also. We can get or set value in a static variable by accessing it with the class’s name e.g. “
in below example”.
Static variable are those variable which can get initialized with the help of static block, even before the main function get executes. Static variables can be called in static block, static method and non-static methods.
If class has static variable and if instance of class changes to value of that particular variable then it will get changed for all the instances of that particular class.
Static Block : Static block is used to assign static variable a value even before main function gets loaded.
It used to invoked static method and run it before main method.
Static block is declared using static keyword followed by open close parenthesis. Although it might look like a function to you but it will never return any value like function does.
It will get executed even before the main method. what we can say that it is the first thing get executed from class.
Static Method : Static methods those methods and not dependent on instance of class. They can be accessed with or without instance but mostly those methods are called with class name me example “Math.MAX()”.
If you see Math class in Java, all the methods in math class are static this is the reason we use “Math.” to use method is from Math class.
Static methods can only invoke static methods and static variables.
Static variables can be called in static block, static method and non-static methods.
In Java we all know that we have to declared a “main” method using static key word, and we have to name that particular file with the name of the class which has main method.
Once you understand static keyword working you will understand why we declare main method using static and also why we supposed to name a file with the class’s name which contains “main” method.
It helps compiler to find “main” method. What compiler does during execution, it takes the name of the file( file is named after the class which has main method ) and add “.main()” after that, so compiler is calling main method with help of class.
name of class which has main method is “StaticDemo”
compiler will take file name i.e. “StaticDemo” and add “.main()” to it.
this will invoke the main method and will get executed.
Execution is possible only because static keyword,
because once you’ve declared any method or any variable using static keyword it can be invoked or accessed using class name. This is the reason why we should name a file with that classes name which contains main method because it helps compiler to run main method.