"Hello, Amigo! I heard Rishi explained something new and exciting to you?!"

"That's right, Kim."

"My topic will be no less interesting. I want to tell you about how classes are loaded into memory."

Classes in Java are files on the disk that contain bytecode, which is compiled Java code.

"Yes, I remember."

The Java machine doesn't load them if it doesn't need to. As soon as there's a call to a class somewhere in the code, the Java machine checks to see if it is loaded. And if not, then it loads and initializes it.

Initializing a class involves assigning values to all of its static variables and calling all static initialization blocks.

"That seems similar to calling a constructor on an object. But what's a static initialization block?"

"If you need to execute complex code (for example, loading something from a file) to initialize objects, we can do it in a constructor. However, static variables don't have this opportunity. But since the need still remains, you can add a static initialization block or blocks to classes. They are basically equivalent to static constructors."

This is how it looks:

Code What really happens
class Cat
{
public static int catCount = 0 ;
public static String namePrefix;

static
{
Properties p = new Properties();
p.loadFromFile("cat.properties");
namePrefix = p.get("name-prefix");
}

public static int maxCatCount = 50;

static
{
Properties p = new Properties();
p.loadFromFile("max.properties");
if (p.get("cat-max") != null)
maxCatCount = p.getInt("cat-max");
}

}


class Cat
{
public static int catCount;
public static String namePrefix;
public static int maxCatCount;

//Static constructors aren't allowed in Java,
//but if they were, everything
//would look like this
public static Cat()
{
catCount = 0;

Properties p = new Properties();
p.loadFromFile("cat.properties");
namePrefix = p.get("name-prefix");

maxCatCount = 50;

Properties p2 = new Properties();
p2.loadFromFile("max.properties");
if (p2.get("cat-max")!=null)
maxCatCount = p2.getInt("cat-max");
}
}
undefined
4
Task
Java Core, level 5, lesson 7
Locked
Code entry
Your attention, please! Now recruiting code entry personnel for CodeGym. Turn up your focus, let your fingers relax, read the code, and then... type it into the appropriate box. Code entry is far from a useless exercise, though it might seem so at first glance: it allows a beginner to get used to and remember syntax (modern IDEs seldom make this possible).

It's a lot like what happens when a constructor is called. I've even written it as a (nonexistent) static constructor.

"Yes, I get it."

"Very good."