Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: `static` Methods

When I call a static method like:

Something.action();

Since a instance isn't created how long will the Class of the static method be held in memory?

If I call the same method will the Class be reloaded for each call since no instance exists?

And are only individual static methods loaded when called or are all the methods and static methods of a Class loaded into memory even though only one static method maybe used?

like image 731
Ande Turner Avatar asked Nov 18 '08 12:11

Ande Turner


People also ask

What are static methods in Java?

A static method in Java is a method that is part of a class rather than an instance of that class. Every instance of a class has access to the method. Static methods have access to class variables (static variables) without using the class's object (instance). Only static data may be accessed by a static method.

Why static methods are used in Java?

A static method has two main purposes: For utility or helper methods that don't require any object state. Since there is no need to access instance variables, having static methods eliminates the need for the caller to instantiate the object just to call the method.

Does Java have static methods?

Java allows developers to define static methods, which are also available to every instance of a class. In an instance of a class, static methods cannot access variables in an instance and those belonging to a class. They can only access static fields and have to use object reference.

When should a method be static Java?

You should consider making a method static in Java : 1) If a method doesn't modify the state of the object, or not using any instance variables. 2) You want to call the method without creating an instance of that class.


1 Answers

Unless you have configured garbage collection of permgenspace, the class stays in memory until the vm exits. The full class is loaded with all static methods.

like image 104
krosenvold Avatar answered Sep 26 '22 19:09

krosenvold