Summary of small points in Java

  • 2020-04-01 02:10:35
  • OfStack

Declare that local variables are features and rules
(1) declared local variables will not be initialized by default, while member variables will be initialized by default. Such as:


class Demo {   
      public static void main(String[] args) {
           String s;
           System.out.println(s);
     }
}

In the above sample code, the direct output s is wrong, even the compilation is different, because s is declared in the main method, where s is a local variable and is not initialized by default, so there is an error in the direct output below. Rewrite the code as follows:

class Demo {   
      String s;
      public static void main(String[] args) {
           System.out.println(s);
     }
}

The output is null because s is declared as a member variable, so the default value is null.
(2) before declaring local variables, there can be no permission to access modifiers (public, protected and private), which can only be the default friendly of friendly, but final can be used to modify local variables.

Use final to modify the difference between local variables of primitive types and local variables of reference types
(1) when final modifies local variables of basic types, the data values of their basic types cannot be modified. Because final modifiers are final, they cannot be changed. The following code:


public class Something {
   public int addOne(final int x) {
       return ++x;
   }
}

The addOne method here USES final int x as an argument, and it is an error to self-increment it next.

(2) when final modifies a local variable of a reference type, that is, an object. You can change the property information in the object, but you cannot change the reference to the object. For example, the following code:


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 accepts an object as an argument, and the value of attribute I in the object is added to the body of the method, and the reference address of the object is not modified, so no error occurs. If I write: o = new Other(); That's when you get an error.

(3) member variables declared by final modifiers ina class do not initialize by default. Therefore, a specific value must be given before the constructor. For example, the following code:


class Something {
    final int i;//This line has reported an error, the compilation cannot pass, there is no initialization value
    public void doSomething() {
        System.out.println("i = " + i);
    }
}

Final int I is a final instant variable. Final instant variable has no default value and must be assigned an explicit value before the constructor (constructor) ends. I can change it to "final int I =0;" .


Related articles: