Variables in Java have member variables and local variables, variables defined in the class are either member variables or Member fields (fields) that represent the properties that a class has, the variables that are defined as member variables of the class, and the entire class, which does not need to be initialized at the time of definition, Before use, Java automatically initializes member variables, which are automatically initialized for the base data type as follows:
Java Basic Type default initialization value
| Int |
0 |
| Short |
0 |
| Byte |
0 |
| Long |
0 |
| Float |
0.0 |
| Double |
0.0 |
| Boolean |
False |
| Char |
0 |
For example:
Public classtest{Private inti; Private Shortm; Private byteN; Private Longl; Private CharC; Private floatF; Private DoubleD; Private Booleanb; Public Static voidMain (String args[]) {System.out.println (i); System.out.println (m); SYSTEM.OUT.PRINTLN (n); System.out.println (l); System.out.println (c); System.out.println (f); System.out.println (d); System.out.println (b); } }
The output of the above code will be the default initialized value;
Variables of reference types are initialized to NULL by default, although Java automatically initializes member variables, but automatic initialization brings some errors, so it's best to initialize the variables before using them to ensure that they are used to the effect they want. The default initialization function is only valid for Java member variables, and if you want to use a local variable you must initialize it, you will get a compilation error.
Java and C languages use curly braces to differentiate between the start and end positions, and the variables in the code block are only valid until the end of the code block, which is not visible after the block has been exceeded, which is not available, and for the object its scope is always visible knowing that the object was reclaimed by the garbage collector, for example:
string S1 = new string ("Hello world!");
The visibility of the reference variable S1 disappears at the end of the scope of the device, but the string object that is created will persist in memory until the Java garbage collector reclaims its memory, although the string object persists in memory, but because there is no reference to the object, Therefore, the object is not available.
Default initialization of Java variables and scopes and member variables