Declaration, memory allocation, and initialization of Java variables
Class person
{
String name;
int age;
void talk ()
{
System.out.println ("I am: +name+", this year: "+age+");
}
public class Testjava2_1
{public
static void Main (String args[])
{person
p;
if (p = = null)
{
p = new Person ();
}
P.name = "John";
P.age =;
P.talk ();
}
To get a better idea of how variables are used in Java, let's do an experiment. Save the above code as a Testjava2_1.java file, and then execute the "javac Testjava2_1.java" command to compile the code into a binary file. The error will be correct at compile time, the error content is roughly as follows:
' testjava2_1.java:59: Error: Variable p may not have been initialized
The compiler thinks that the reference data type variable p is not initialized, so it is not possible to determine whether it is equal to NULL, but I do not think the compiler is accurate in its presentation of this error. Even if the variable p does not give the initial value and the default value is at least present, then what is not possible with the default value and null comparison? I think the correct error statement should be "variable p has not allocated memory space". "Person P" simply declares that there is a reference data type variable p, but does not allocate any memory space to P, which is different from C + +.
When the declaration of the variable p is changed to "person p = null", the execution of "Javac Testjava2_1.java" can be compiled successfully. The "person p = NULL" statement, in addition to assigning a variable p initial value, also allocates memory space for the variable p before assigning it.
As you can see from the experiment above, the memory allocation of reference data type variables in Java occurs when the initial value is assigned. Testing the basic data type variables in Java in the same way, you can also find that the variables are not allocating memory when they are declared, and that the true memory allocation occurs when the initial value is assigned.
Note that there is an error on the above, if it is int A;
The A variable is allocated to the memory unit. A default value is 0;
So the base type allocates the memory unit when it is declared.