In JAVA static can be used in three way,
’static’ is a predefined keyword of JAVA, and it is used to make variables and methods static.
static keyword is used when you want actual value of method which, because you can access method outside class without making instance of a class this means you will directly call to that method, and value of that method will not change. for example :
suppose You have a method which will fetch data from internet and store it in a variable. Now you want to get value of that variable in another class, then you can make that method “static” and you can get its values by this syntax : ClassName.variableName;
public class Test{static String msg = "Hello"; // static variable;static void getMsg(){// this is static method.}}
public class Message{String value = Test.msg; // get value from first class, and store in value string;System.out.println(value); // print value of value string.}
To create java static method we simple use ’static’ keyword, and if your methods have some non-static methods or variables then also make then static, because static method can access only static fields.
Syntax of creating static method in non-static class:
public class Main {public static void main(String[] args) {Test.getData(); // calling static method from another class directly using class nameSystem.out.println(Test.sum); // accessing sum variable from another class}}class Test{static int a = 10;static int b = 8;static int sum;public static void getData(){sum = a+b;}}
So in the given example I have 2 java classes ’Main’ and ’Test’, and inside the ’Test’ class I have some static variables and 1 static method. And I am calling that method and variable in ’Main’ class without creating an instance of ’Test’ class. But if that variables and method should be non-static then its impossible to class them without creating an Instance of ’Test’ class.
Quick Links
Legal Stuff
Social Media