Understanding static keyword in java

Shubham Dadasaheb Sawant
3 min readJun 15, 2022

There are static block, static variable and static method

A. Static blocks:

  1. Block containing static keyword.
  2. This block is executed immediately when class is loaded in the memory. Even before the main method .
  3. One class can contain multiple static blocks.
  4. Can we print something on console without main method
    1. If JDK version is ≤ 1.6 you can else not

B. Static variable:

  1. Static variables are variables that belong to class and not object.
  2. Initialized only oncee at the start of the program.
  3. Before any other variables this variables are initialized.
  4. Single copy of this variable is shared by all instances of class.
  5. No need to create any object for accessing it can be easily accessed by
    classname.staticvariable_name.

Need of static variable ?

Your class contains 100 students each student can have unique rollno and unique name. its oky so we need to create 100 entries for rollno and 100 for name. But is it required to create 100 college name entries ? Ofcourse the answer is no.
so in order to save memory we can say static variable is used so above code is modified as static String college.

6. Static variables can be directly accessed in static method.

7. static variable copy is shared among all objects.

8. Static variables are initialized when class is loaded.
9. Static variables are initialized before any object of that class is created.
10.Static variables are initialized before any static method of the class executes

MCQ Practice on Static Variables:

1.

==> Error as a , b must be static to be accessed in main()

2.

Output: 1 5

3.

OUTPUT:
2 2

4.

OUTPUT: 7 9

More static based coding mcq problems
https://www.geeksforgeeks.org/output-java-programs-set-48-static-keyword/

C. Static Methods:

  1. This method is accessible to every instance of class. You can access this methods without creating objects.
  2. Instance methods are only accessible using objects.
  3. Static method is part of class definition and not part of object.
  4. This method doesn’t require any invocation object.
  5. They are accessible by classname.static_method_name;

OUTPUT:

Happy Coding !!

--

--