The source code is as follows , Find the result

public class MemoryAnalyse {
public static int k = 0;
public static MemoryAnalyse t1 = new MemoryAnalyse("t1");
public static MemoryAnalyse t2 = new MemoryAnalyse("t2");
public static int i = print("i");
public static int j = print("j");
public static int n = 99; {
print("constructor code");
} static {
print("static code");
} public static int print(String s) {
System.out.println("i=" + i + "   " + s + "  k=" + k + "  n=" + n
+ "   j=" + j);
++i;
++k;
++n;
return i;
} public MemoryAnalyse(String string) {
print(string);
} public static void main(String[] args) throws ClassNotFoundException {
MemoryAnalyse d = new MemoryAnalyse("T");
}
}

Source download

But it turns out that

i=0   constructor code  k=0  n=0   j=0
i=1   t1  k=1  n=1   j=0
i=2   constructor code  k=2  n=2   j=0
i=3   t2  k=3  n=3   j=0
i=4   i  k=4  n=4   j=0
i=5   j  k=5  n=5   j=0
i=6   static code  k=6  n=99   j=6
i=7   constructor code  k=7  n=100   j=6
i=8   T  k=8  n=101   j=6

Are you surprised , It turns out to be so complicated . good , Let's analyze , Before analysis , First popularize the basic knowledge that is not very useful

When code blocks and static code blocks run :

The code block runs when the object is created
Static code blocks run when classes load

Everybody knows static Is a class, not an object , in other words static All the embellishments will be in class It's there when it's loaded into the method area . So in the method area Class load time memory procedure as follows

1. When the class is just loaded, it will all be loaded into the method area , At this point, all variables are not instantiated .

2. Instantiate parameters t1

At this point, because the code block executes when the object is created , And execute before the constructor , So execute the code block first

{
print("constructor code");
}

Because at this time all variables are default values , So the print result after execution is

i=0   constructor code  k=0  n=0   j=0

here i,n,k All the values of have been added by themselves , The value is 1

Then instantiate and call the constructor

public MemoryAnalyse(String string) { // here string by t1
print(string);
}

The result of the constructor call is as follows

i=1   t1  k=1  n=1   j=0
here i,n,k All the values of have been added by themselves , The value is 2

3. Instantiate parameters t2

As in the first step, execute the code block before the constructor

{
print("constructor code");
}

i=2   constructor code  k=2  n=2   j=0

here i,n,k All the values of have been added by themselves , The value is 3

Then instantiate and call the constructor

public MemoryAnalyse(String string) { // here string by t2
print(string);
}

The result of the constructor call is as follows

i=3   t2  k=3  n=3   j=0

here i,n,k All the values of have been added by themselves , The value is 4

4. Initialize parameters i

Call directly here print("i") function , The result is

i=4   i  k=4  n=4   j=0

here i,k,j The value is 5, Be careful i The value of is not changed by adding one to itself 5 Of , It's assigned to... By the return value of the function i Of

5. Initialize parameters j

This is the same as the previous step , perform print("j"), Then assign the return value of the function to j, The result is

i=5   j  k=5  n=5   j=0

here j The value of is already 6

Here, the internal parameter changes of class loading are completed , We can call it by loading the class

 public static void main(String[] args) throws ClassNotFoundException {
//MemoryAnalyse d = new MemoryAnalyse("T");
Class.forName("MemoryAnalyse");
}

Class.forName( Class name string ) Is to manually load the class into the method area , The result is

i=0   constructor code  k=0  n=0   j=0
i=1   t1  k=1  n=1   j=0
i=2   constructor code  k=2  n=2   j=0
i=3   t2  k=3  n=3   j=0
i=4   i  k=4  n=4   j=0
i=5   j  k=5  n=5   j=0
i=6   static code  k=6  n=99   j=6  // This line of business comes out of static The code snippet executes when the class loads .n=99 Because the class is loaded ,n The initial value for the 99 The previous value has been overridden

Then change to our previous demo

public static void main(String[] args) throws ClassNotFoundException {
MemoryAnalyse d = new MemoryAnalyse("T");
//Class.forName("MemoryAnalyse");
}

The execution result is

i=0   constructor code  k=0  n=0   j=0    //t1 Code block execution
i=1   t1  k=1  n=1   j=0  //t1 Constructor execution
i=2   constructor code  k=2  n=2   j=0   //t2 Code block execution
i=3   t2  k=3  n=3   j=0  //t2 Constructor execution
i=4   i  k=4  n=4   j=0
i=5   j  k=5  n=5   j=0
i=6   static code  k=6  n=99   j=6  // Static code block execution
i=7   constructor code  k=7  n=100   j=6    //T Code block execution
i=8   T  k=8  n=101   j=6     //T Constructor execution

The last two lines are very simple , One is a block of code , One is a constructor

Is this analysis a lot simpler

It's very muddled java Memory load interview questions more related articles

  1. It's very testing java Memory loading interview questions

    The source code is as follows , Find the result public class MemoryAnalyse { public static int k = 0; public static MemoryAnalyse t1 = new ...

  2. java Memory loading mechanism

    What is? java Class loading ? Class loading means loading .class The binary data in the class is stored in memory , It will create one in the push in memory java.lang.String To store the data structure of the method area , The data in the class is put in the method area Analogous addition ...

  3. 【 Design patterns 】C++ Several ways to write the singleton pattern ——Java Automatically load inner class objects ,C++ How to deal with it ?

    Singleton is the simplest design pattern , Let me write it down like a simple game . v1: Simple mode I met this version , But I don't agree . class Singleton { private: Singleton() { ...

  4. It turns out that thermal loading is so simple , Write one manually Java Thermal loading

    1. What is hot loading Hot load means that the changed code can take effect without restarting the service , Hot loading can significantly improve the efficiency of development and debugging , It is based on Java Class loader of , But because of the insecurity of hot loading , It's not normally used in a formal production ring ...

  5. Java Load classes dynamically

    See :https://blog.csdn.net/zai_xia/article/details/80026325 Expand :java Reflection mechanism and dynamic loading class  https://www.cnblogs.com/ ...

  6. java class Loading mechanism and object generation mechanism

    java class Loading mechanism and object generation mechanism When using a class , But the class is not initialized yet , Class loading occurs when it is not loaded into memory . link . There are three steps to initialize the class . It should be noted that the order of class initialization and linking may be interchangeable . Cl ...

  7. Memory load DLL

    1. Preface There are a lot of sensitive and important DLL(Dynamic-link library) There is no static version for the compiler to connect statically (.lib file ), Even if the static version is provided, it cannot be used due to compatibility problems , And only provide DLL ...

  8. Java Virtual machine load class

    Java How does the virtual machine load Java Class Java Virtual machine loading Java Class needs to go through 3 Step : load ----- link ----- initialization .Java There are two types of languages : Basic types and reference types . The basic type is that there are Java virtual machine ...

  9. Java ClassLoader Loading mechanism understanding

    I saw an introduction today Java ClassLoader Loading machine articles , Only then discovered has come own shallowness , I learned a lesson well , Had to file ! Original address : http://www.blogjava.net/lhulcn ...

Random recommendation

  1. Eclipse+Python+Selenium Automatic test framework construction

    1. download Eclipse:http://www.eclipse.org/downloads/ 2. download JDK:http://www.oracle.com/technetwork/java/javaee/ ...

  2. 7. Summary of internal sorting algorithms ( Insertion sort 、Shell Sort 、 Bubble sort 、 Please select category 、、 High speed sorting merge sorting 、 Heap sort )

    Write it at the front : Sorting is an important operation in computer programming , Its function is to put a random sequence of data elements , Again in a row by keyword Ordered sequence . Therefore, it is very important to master various sorting algorithms . Sort the items described below , Let's assume that all of them are ...

  3. EsRejectedExecutionException Debugging and thread pool type

    1.EsRejectedExecutionException Exception example java.util.concurrent.ExecutionException: RemoteTransportException ...

  4. Java Description of the data structure of the list of additions, deletions, changes and queries

    Linked list is a common basic data structure , It's a linear table , But it's not stored sequentially in memory , It is stored in chains , Each node stores the next node's " The pointer ". stay Java The data in is divided into reference data type and base ...

  5. Transactions and their characteristics ACID

    One . Definition of transaction A transaction is a set of unitary operations , This set of operations is guaranteed to be either all successful , All or nothing ( As long as there is a failed operation , It will roll back other successful operations ). Generally speaking, database transaction , It is to access and possibly update various data items in the database ...

  6. 4.1 ORACLE DATAGUARD SWITCHOVER step

    Verify whether the primary library can perform role transition to the secondary library The original main library performs SQL> SELECT SWITCHOVER_STATUS FROM V$DATABASE; SWITCHOVER_STATUS --------- ...

  7. Learning notes CB004: put questions to 、 retrieval 、 answer 、NLPIR

    chatbot , put questions to . retrieval . answer . put questions to , Query keyword generation . The answer type is determined . Syntactic and semantic analysis . Query keyword generation , Question extraction keywords , The head word is associated with the extension word . The answer type is determined , Determine the type of question . Syntactic and semantic analysis , Analysis of the deep meaning of the problem . retrieval ...

  8. ASP.NET MVC+HighCharts Develop statistical charts

    HighCharts It's open source. Web Chart js Components , And D3.js equally , Often used for data visualization .HighCharts There are many types of charts , Very powerful , It's a good data visualization solution , Its official website is :http://www.h ...

  9. ngnix An example of using timeout response time to configure pit avoidance

    ngnix The timeout response time of is better than tomcat Of spring mvc The response time is still small , The tragedy happened , The production environment is not easy to find . It's like customizing a fixed wooden cabinet without considering the size of the door , I can't get in either way , It's tragic . Ha ha ha , Take this as a reference !~

  10. UML And mode applications 5: Refinement stage (6)--- Operating contracts

    1. Preface Operational contracts use pre - and post conditions , Describe the detailed changes of objects in the domain model , As a result of system operation . Operational contracts can be useful OOA Related products . Operation contract can be regarded as UP Part of the use case model , It's the utility of operating the system where the use case is ...