variable
The concept of variables
- Variables are used to declare a certain memory block in memory to be used by the program
- The data in this area can be constantly changing within the same type range
- Variables are the most basic storage unit in a program. Contains the variable type, variable name and stored value
. The role of the variable is
used to store data in the memory.
Notes on using variables - Variables in java must be declared before use
- Use variable names to access data in this area
- The scope of the variable: within the pair {} where it is defined
- Variables are only valid within their scope
- Variables with the same name cannot be defined in the same scope
Variable declaration
syntax: data type variable name;
variable assignment
variable name = value;
example:
public class Demo{
public static void main(String[] args){
//声明变量
int var;
//给变量赋值
var = 12;
}
}
Declare variables and assign values
Syntax: data type variable name = value;
example:
public class Demo{
public static void main(String[] args){
//声明变量并赋值
int var = 12;
}
}
Classification of variables by data type Variables of
basic data types: byte variables, integer variables, long integer variables, etc. Variables of
reference data types: later explanations
are classified according to the position of declaration
Member variables: variables declared outside the method body and inside the class
Local variables: Variables declared inside the method body
The difference between member variables and local variables: (Additional later)
- Different locations: local variables are written in methods; member variables are written directly in classes
- The default values are different: member variables have default values; local variables have no default values, and must be assigned before they are used.
- Different scope: local variables are only valid in methods; member variables are valid in all methods
- Access modifiers are different: local variables cannot use access modifiers; member variables can use access modifiers
- Local variables cannot use static, member variables can use static (class variables)
constant
Unlike variable constants, once a constant is defined and assigned, the value in the memory cannot be reassigned.
classification
- Literal constant: is the literal meaning, such as: 123, "ABC", "中", etc.
- Symbolic constants:
the definition of constant constants represented by
symbols.
Examples of using the keyword final when defining symbolic constants :
public class Demo{
public static void main(String[] args){
//定义常量
final int num =12;
//以下代码编译错误:常量不能重新赋值
//num = 13;
}
}