0

I have a java library of classes with lots of static methods that do things like getRandom numbers between a range, populate arrays with random numbers, find number statistics of arrays like average and median, getValid keyboard input ect... My question is since there static methods can be used without an import statement and does not need to be instantiated with the new keyword, Is this library taking up more memory for its methods if I only need to use one method in my program

If I am being ambiguous, This is what I mean. I am creating a my own java utility library that have many utility methods. It might have say 100 methods, I will call it LIBRARY X. Now I am making a new program PROGRAM Y. Program Y used only 1 method out of 100 from Library X, will program Y load all 100 methods if I only need 1. How can I avoid loading the whole library if its not needed, or does java load only the methods invoked by the program already.

user3094038
  • 101
  • 5

3 Answers3

1

since there static methods can be used without an import statement

This is wrong in most cases. In Java, static methods need to be contained in a class, and of course most of the time, those classes must be imported. Instances of this class do not need to be instantiated in order to call those methods.

If you group one method per class (in this example), and only call one method, then only one class is loaded and thus needs less memory.

But you should really not care about code memory consumption.

And, to be honest: 100 methods is not much.

tilpner
  • 4,351
  • 2
  • 22
  • 45
1

As far as I know, all the static contents as well as static blocks of a class are initialized when a ClassLoader loads the class into memory.

Unless you are developing for embedded devices where memory is precious than you should not care.

What you should care tough is if your class is becoming a god class. Even if it is an utility class it should only contain methods for a certain purpose.

Ex:

StringUtil would contain static methods for string manipulation.
Math2 would contain additional math utility methods.
ValidationUtil would contain methods destined for validation.

What you could do that would make your code look cleaner in some situations would be to use static imports where you need to use the methods.

DO NOT ABUSE STATIC IMPORTS

If you abuse them for every static method or so, your code will become harder to maintain and read.

Andrei
  • 3,086
  • 2
  • 19
  • 24
0

Have a read of this post, static variables are stored where in the PermGen section because they are static they are not created again for every instance of the class so could save memory if you were creating many instances of the class.

Community
  • 1
  • 1
Basim Khajwal
  • 946
  • 6
  • 6