Variables in the Java language must be defined before use. The general way to define variables is:
Type variable name;
Types include int, short, char, etc., all of which are fixed (we will introduce them in detail in the next section). We need to choose what type according to the actual situation. Different types represent the size of the variable and have corresponding data range. The variable name is the name given by our users, which can be named by our programmers. However, in order not to cause conflicts, this name follows the requirements of identifiers , namely:
1) The first character must be a letter, underscore (_), dollar sign ($) or RMB sign (¥).
2) The identifier consists of numbers (0~9), uppercase letters (A~Z), lowercase letters (a~z), underscores (_), dollar signs ($), RMB signs (¥), and all hexadecimal characters. It consists of the ASCII code before 0xc0.
3) The name cannot overlap with keywords or reserved words.
4) There is no limit on the length of identifiers.
5) Identifiers are case-sensitive.
Next we can try to define a variable such as an integer, as follows:
intnumber;
That is, the integer variable keyword int space number, where number is the name we gave ourselves. Note that it must end with an English semicolon. You can try to define other variables on the computer yourself.
Obviously, if we name the variable char, such as:
intchar;
Obviously, this is wrong because it has the same name as the identifier.
Assignment and initialization of variables
In Java, there are two types of variable assignments. The first is to assign a value when the variable is defined, which is also called initialization . The second is to assign a value in a single assignment statement. The assignment is performed using the assignment operator (=) .
For example, the variable number above can be assigned as follows:
intnumber=2020;//Initialize to 2020 while defining
Also possible:
intnumber;//Only define the number variable, no value is assigned, the default is 0number=2021;//A single statement assigns the value to 2021
Please try these two methods respectively.
In addition, Java allows you to define multiple variables of the same type at the same time and initialize multiple variables, such as:
intnumber1=1999,number2=2000,number3=2049;
This method is also possible. You can use it according to the actual situation. You need to pay attention to that the variable must be assigned a value before using it. Otherwise, the number of the variable itself is meaningless and you will not get the desired result.
I hope you can practice more based on your understanding.