How to use the Java static keyword?
In Java, the keyword “static” is used to modify members of a class, such as static variables, static methods, and static code blocks.
- Static variables:
Static variables belong to the class rather than the instance, and their value is shared among all instances. They can be accessed directly through the class name without creating an instance of the class. They are modified using the static keyword. - The class named MyClass has a static variable called myStaticVariable.
- The static variable can be accessed through MyClass.myStaticVariable.
- Static methods:
Static methods do not rely on any instance and can be called directly using the class name. They can only access static variables and cannot access non-static variables, because the value of non-static variables is associated with the instance. Keywords: static. - In the class called MyClass, there is a static method named myStaticMethod.
- You can call the static method through MyClass.myStaticMethod().
- Static block:
The static block is executed when the class is loaded, and it only runs once. It can be used to initialize static variables or perform other static operations. It is designated with the keyword “static”. - MyClass class with a static block for implementation.
- The code in a static block will be executed when the class is loaded, allowing for some initialization operations to be performed within it.
It is important to note that static members can be accessed directly by the class name without the need to create an instance, so there is no need to reference them through an object when accessing them. Static members are associated directly with the class, not with instances of the class.