Static keyword

static  keyword s mainly used for memory management. It can be used with variables, method,blocks and  nested class. The static keyword belongs to the class, not to the object of the class.

It can be used with the following:

  1. Variable(also known as class variable)
  2. method (also known as class method)
  3. block
  4. nested class

1. Java static variables:

if you use static keyword with a variable ,that variable is known as static variable.

  • For static variables , memory is assigned only once at the time of class loading.
  • Can be used to refer the common property of all the objects e.g. college for all the students, a garden for walk,library name for all the books etc.

Problem if static not used:

Suppose , there is a book store which has library named as XYZ. There are total 1000 books, in that library each book has unique id and name. So, when the object is created , all the data members occupy memory. As we can see library is common for all the books, we should make it static so it consumes memory only once.

Example of usage of static keyword:

Output: 1–Maths book–XYZ 2–English book–XYZ

2. static methods: If a static keyword is used with method, known as static method.It has the following points to note.

  • A static method can access static data-members and can change its value.
  • Static method belongs to the class, not with the object.
  • Static method can be invoked without using the object of the class.
Output: 1–Maths book–ABC 2–English book–ABC

3. Static block: There are 2 important aspect to understand about the static block.

  1. static blocks get executed before the main method at the time of classloading.
  2. static block can be used to initialize the static data members.
Output: First execute the static block 1–Maths book–XYZ 2–English book–XYZ

Important points to notice:

  • static method can only access static data-members or methods, not the non-static.
  • this and super cannot be used in static context.
Error : Cannot make a static reference to the non-static field name

Can we execute program without main method?

It was possible in JDK version before 1.7. We could have used the static block and execute the program. But in JDK 1.7 it throws an compilation error.

Ask Question
If you have any question, you can go to menu ‘Features -> Q&A forum-> Ask Question’.Select the desired category and post your question.
Print Friendly, PDF & Email
Packages
Main method in java
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *