Link: https://www.cnblogs.com/ipetergo/p/6826909.html
What is the difference between string s; and string S = NULL; and string S = "?
For the three cases, when out. println (s); is used, the first one has an exception, and the second one outputs null. The third one outputs.
Why? What are their respective statements?
A:
The first is to define a string-type variable s without assigning an initial value to it. In Java, the initial value must be assigned when a variable is used by default (to reduce risks ). Both the second and third define the string type variable S and assign it the initial value, except that the second value is null.
The main thing to understand is string s; S is a reference ~~ It is not the first reference of the object that is not initialized; the second is an empty reference;
The third is to write a character 'a' in the string pool and point it to it with S.
In addition, string S = "a" and string S = new string ("A"); are essentially different. The former is to write a character 'a' in the string pool ', then point to it with S;
The latter creates a String object with the content "A" on the stack.
String STR = "AAA"; // allocate memory on the stack
String STR = new string ("AAA"); // allocate memory on the heap
String s; the system automatically assigns null values.
String s; only allocates a memory space for S. String S = NULL. The value stored in the allocated space is null. String S = ""; I don't need to say that the value of the allocated space is character.
Extension supplement:
In the definition of member variables, string s; equivalent to string S = NULL;
In the definition of local variables (method variables), string s; is not the same as string S = NULL; in this case, s must be explicitly assigned a value.
Although these are small knowledge points, they are very important in practical application and are easily ignored by some people.
Another note is:
As long as the initial values are displayed in the variables defined in the method, the main () method is no exception, and the compiler automatically assigns the initial values outside the method.
Difference between string s string S = NULL and string S = ""