Static


Static

Static variable is shared across all the objects. You can only create one copy of a static variable. Furthermore, there is also a possibility to have static block, static method and static class.

Syntax to declare static variable:

static data_typevariable_name;

To make a static member (block, variable, function, nested class), use the keyword static before declaring it. When a member is declared static, it can be accessible before any objects of its class are generated, and it can be accessed without requiring a reference to any object.

Static variable:

When a variable is marked as static, a single copy is made and shared across all objects in the class. Static variables, on the other hand, are effectively global variables. The static variable is shared by all instances of the class. Important considerations for static variables include:

  • Only at the class level can we establish static variables.
  • Static blocks and variables are executed in the order in which they appear in a program.

Static method:

Static methods are those that are declared using the static keyword. The main( ) method is a static method. Static methods are subject to the following constraints:

  • They can only call other static methods directly.
  • They can only access static data directly.
  • They are not allowed to use the words "this" or "super" in any way.

Static Block

Static variables are initialized using a static block. Despite the fact that static variables can be initialized directly upon declaration, there are times when multiline processing is required.

Static blocks are in handy in these situations. A static block can be utilized if static variables require additional, multi-statement logic during setup.

Static Class

We can create a class within a class in the Java programming language. It offers a persuasive approach of grouping items that will only be utilized in one place, making our code more ordered and readable.

Example:

Com.knowledge2life public class Main { static void myStaticMethod() { System.out.println("Knowledge2life"); } public static void main(String[] args) { myStaticMethod(); } }

OUTPUT:

Knowledge2life1