Some characteristics and rules of declaring local variables
(1) Declared local variables are not initialized by default, and member variables are initialized by default. For example:
Copy Code code as follows:
Class Demo {
public static void Main (string[] args) {
String s;
System.out.println (s);
}
}
In the example code above, the direct output s is wrong, and even the compilation is different, because S is declared in the main method, and S is the local variable, not the default initialization value, so the direct output below is incorrect. The code can be rewritten as follows:
Copy Code code as follows:
Class Demo {
String s;
public static void Main (string[] args) {
System.out.println (s);
}
}
This output is null, because S is declared as a member variable, so the default is initialized to the value null.
(2) Declaring a local variable cannot have any permission access modifiers (public, protected, and private) before it can only be friendly-friendly, but you can use final to modify local variables.
Second, use final to modify the difference between the basic type local variable and the reference type local variable
(1) When final modifies the basic type local variable, the data value of its basic type cannot be modified. Because the final modified variable is the ultimate, can not be changed. The following code:
Copy Code code as follows:
public class Something {
public int AddOne (final int x) {
return ++x;
}
}
Here the final int x is used as an argument in the AddOne method, and it is an error to add the following to it.
(2) When final modifies a local variable of a reference type, that is the object. You can modify the property information in the object, but you cannot modify the object's reference. For example, the following code:
Copy Code code as follows:
public class Something {
public static void Main (string[] args) {
Other o = new Other ();
New something (). AddOne (o);
}
public void AddOne (final other O) {
o.i++;
}
}
Class Other {
public int i;
}
Here the AddOne method receives a parameter that is an object, and the value of attribute I in the object is added to the method body, and the reference address of the object is not modified so that no error occurs. And if you write in the body of the method: O = new Other (); Then it will be an error.
(3) The member variable declared in the class by the final modifier does not initialize the value by default. Therefore, a specific value must be given before the constructor. For example, the following code:
Copy Code code as follows:
Class Something {
Final int i;//This line has an error, the compilation does not pass, there is no initialization value
public void dosomething () {
System.out.println ("i =" + i);
}
}
Final int i is a final instant variable (instance variable, or called member variable). The final instant variable does not have default value and must be given a definite value before the end of the constructor (constructor). Can be modified to "final int i = 0;".