Problem
When I recently wandered around the CSDN forum, I saw a friend asking for some basic knowledge, and just recently I was learning the basics of Java, so I tried to summarize the problem with the array declaration from the memory point of view.
@Test void Test(){ Stringnull; p = {"no"};//这种不指定数组下标初始化的方式只在下一行这种格式中适用 StringnewString[]{"no"}; p[0"y";//此处编译可以通过,但是运行通过不了,无法输出p[0]的值 newString[]{"yes"};//这种方式就完全没问题,编译和运行都pass }
Summarize
- In fact, this kind of problem from the internal analysis of classes and objects is very well understood, the first thing to know is
Stack: Local variables, reference names of declared objects, reference names of arrays, parameters in defined class methods, and local variables
Heap: New "things" (e.g. entities of objects, entities of arrays), with member variables (so-called global variables)
* Immediately after the object's reference is associated with the object's entity: The object reference in the stack holds the first address of the entity in the heap, so it can be compiled and run normally.
*
* You give the analysis of the problem:
* First, no new operation, so {"No"} is not saved in the heap, so this method is not possible
* The second kind, with the first kind is actually a problem, just the second kind of compilation can be done by
* The third type, which is usually the step of declaring an array and initializing it, contains three parts:
* 1) Declare the reference name of an object in the stack (this step is reflected in the first line string[] p = null, when p is the reference name of an array object)
* 2) Create an entity of a string array in the heap (this step is reflected in the new string[]{"Yes"})
* 3) Assign the first address of the entity to the reference of the object (this step is reflected in the = sign in P = new string[]{"Yes"})
* Presumably, through internal analysis you should be able to easily understand the difference.
[Java] Array declaration for problem analysis