简体   繁体   中英

When is memory created for static methods in Java

I have two classes A and B. Class A has main method and class B has two methods namely, Add and Sub .

My question is, when is the memory allocated for class B?

At Line no. 2 or 8; when I import the class or when I call the class?

If the memory is allocated at line no. 2. At line no. 3 I have imported java.util.* so object will be allocated for all the class in util package.

If the memory is allocated at line no. 8 then what about the sub method?

Class A

   1 package sample;
   2 import sample1.B;
   3 import java.util.*;
   4 public class A 
   5 {
   6    public static void main(String args[])
   7    {
   8        B.Add(3, 3);
   9    }
   10 }

Class B

package sample1;
public class B 
{
    public static int Add(int A,int B)
    {
        return A+B;
    }
    public static int sub(int A,int B)
    {
        return A-B;
    }
}

Line two is not code that translates into JVM bytecode instructions. It's merely a declaration to the compiler to help it resolve simple names.

Immediately before line eight is the latest possible moment when the ClassLoader for B will run and the static initializers (if any) for B will run. Execution of the ClassLoader for B , however, could occur earlier. The specification merely guarantees that a Class object will be loaded once and only once and not later than before its first use and that the static initializers will run once and only once and immediately before the first moment where they are needed.

At line no 3 i have imported java.util.* so object will be allocated for all the class in util package.

No, again, an import declaration does not translate into JVM bytecode instructions. It does not cause any objects to be created or loaded at runtime. It is only a declaration that the compiler uses to resolve simple names. This is so you can say Set instead of java.util.Set .

If the memory is allocated at line no 8 then what about the sub method?

The ClassLoader for B and the static initializers for B will run before line eight is executed, and they will not be run again if you invoke any additional static members of class B .

Memory (for statics and assorted control info) is allocated for a class when the class is loaded.

Memory is allocated for an instance when the instance is created (ie, new ).

Memory is allocated for a method when the method is invoked. (And it doesn't matter whether the method is a static or instance method.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM