DEV Community

Anees Abdul
Anees Abdul

Posted on • Edited on

Static/Non-Static Block

What is a Static Block:

  • It is a block of code that runs once when the class is loaded into memory, without creating an object.
  • Static block runs before main().
static{
//code}
Enter fullscreen mode Exit fullscreen mode

What is a Non-Static Block:

  • It is a block that runs whenever an object is created.
  • It runs before the constructor.
{
//code
}
Enter fullscreen mode Exit fullscreen mode

What is a Static Variable:

  • A static variable is a class-level variable declared using the static keyword, shared by all objects of the class.
  • We access it using ClassName.variableName
  • Static variables are stored in the method area (class area).
class Student {
    static String school = "ABC School";
}
Enter fullscreen mode Exit fullscreen mode

What is a Static Method in Java?

-A static method is a method that belongs to the class, not to objects.

  • We can access it without creating an object.

Top comments (0)