2

I have a class:

public class Foo {
    public static boolean flag = false;
    //some code
}

I am using this boolean flag in another class:

public class FooImpl{
    public static void main (String args[]) {
        if (Foo.flag){
            //Line 1
            //some code
        }
    }
}

So at Line 1, does class Foo gets fully loaded in the memory or just the static variable gets loaded with default value?

pcnThird
  • 2,362
  • 2
  • 19
  • 33
Sambhav
  • 217
  • 2
  • 16
  • i think you can take some understanding from this [link][1] [1]: http://stackoverflow.com/questions/6569557/what-is-the-actual-memory-place-for-static-variables – ppuskar Jan 21 '14 at 06:13

2 Answers2

3

A classes static initialization normally happens immediately before the first time one of the following events occurs:

  • an instance of the class is created,
  • a static method of the class is invoked,
  • a static field of the class is assigned,
  • a non-constant static field is used, or

See JLS 12.4.1.

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
-3

The class gets loaded when there is a static reference to the class. It is loaded by ClassLoader [java.lang.ClassLoader].

when you access a class member or constructor [creating an instance of that class] you need information about the class and it gets loaded.

you might have seen some ClassNotFoundException for some library function calls. The ClassLoader is behind that.

But there is other fact that the class gets initialized when something in the class is used first.

Initialization of a class consists of executing its static initializers and the initializers

for static fields (class variables) declared in the class.

In line 1 you are referring to a member of class and its loaded for sure.

Initialization Occurs:

T is a class and an instance of T is created.

  • T is a class and a static method declared by T is invoked.
  • static field declared by T is assigned.
  • A static field declared by T is used and the field is not a constant variable
  • T is a top level class, and an assert statement lexically nested within T is executed.

A reference to a static field (§8.3.1.1) causes initialization of only the class or interface that actually declares it, even though it might be referred to through the name of a subclass, a subinterface, or a class that implements an interface.

Dineshkumar
  • 4,165
  • 5
  • 29
  • 43
  • 1
    Downvote is welcomed if they let me know the mistakes so that everyone can learn including me. – Dineshkumar Jan 21 '14 at 05:26
  • 2
    I am not the downvoter and I agree with your sentiment. I do however find your answer difficult to read. – Scary Wombat Jan 21 '14 at 05:29
  • 1
    The class gets loaded when there is *any* reference to the class that hasn't already been satisfied, whether static or otherwise. Your edit contradicts your original answer. What remains is poorly expressed. -1 – user207421 Jan 21 '14 at 05:48