Variables in ava include member variables and local variables. Variables defined outside methods in the class become member variables or member fields (domains), representing the properties of a class. The function of the variable defined as a member variable of the class is the entire class. This variable does not need to be initialized when defined. Java will automatically initialize member variables before use. The automatic initialization of basic data types is 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 class test{ private int i; private short m; private byte n; private long l; private char c; private float f; private double d; private boolean b; public static void main(String args[]){ System.out.println(i); System.out.println(m); System.out.println(n); System.out.println(l); 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;
For variables of reference type, the default initialization is null. Although Java will automatically initialize member variables, automatic initialization will bring some errors. Therefore, it is best to initialize variables before using them to ensure that the use of variables meets the effect you want; the default initialization function is only valid for Java member variables. If you want to use local variables, you must initialize them, otherwise you will get a compilation error.
Java, like C language, uses curly braces to distinguish the starting and ending positions. The variables in the code block are only valid before the end of the code block. After exceeding the code block, the variable is invisible, that is, it is unavailable. For the object, its scope is always visible and knows that the object has been recycled 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 user scope, but the created String object will remain in memory until the Java garbage collector recycles its memory. Although the String object will always exist in memory, it is unavailable because no reference points to the object.
The above article is based on Java variables, scope and member variables default initialization (detailed explanation) is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.