4

Say that I have a Java project with some "Utils" classes, and that those classes have only static methods and members.

Once I run my application, are those methods and members automatically loaded into memory? Or that only happens once I call the class along the code?

EDIT: Some sample code to illustrate my question.

RandomUtils.java

public class RandomUtils {

    private static Random rand = new Random();

    public static int randInt(int min, int max) {
        // nextInt is normally exclusive of the top value,
        // so add 1 to make it inclusive
        return rand.nextInt((max - min) + 1) + min;
    }
}

MainClass.java

public class MainClass {
        public static void main(String[] args) {
            // Some other operations. Is my class already loaded here?

            int randomNumber = RandomUtils.randInt(1,10); // Or is it only loaded here?
        }
}

And what if that class have other static members and methods, and if it loads only once I call one of them, the other methods are loaded as well?

Mauker
  • 11,237
  • 7
  • 58
  • 76
  • 2
    Downvoter, could you explain what's the problem? – Mauker Jan 11 '16 at 13:43
  • 1
    For a general discussion see: http://javarevisited.blogspot.com/2012/07/when-class-loading-initialization-java-example.html – mhp Jan 11 '16 at 13:46

4 Answers4

4

Static methods (and non-static methods, and static/member variables) are not loaded into memory directly: the declaring class is loaded into memory in its entirety, including all declared methods and fields. As such, there is no difference in the way that static/non-static methods/fields are loaded.

A class is only loaded by a class loader the first time it is referenced by other code. This forms the basis of the Initialization on demand idiom.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
2

Your class is loaded when (among other conditions) its static method is called for the first time. See reference.

dejvuth
  • 6,986
  • 3
  • 33
  • 36
1

static methods loads only once when you call class.enter image description here

college="ITS" is an static variable

Mahesh Giri
  • 1,810
  • 19
  • 27
0

it happens once you call the class.

Mehdi TAZI
  • 575
  • 2
  • 5
  • 23