8--variables and constants

variable

The concept of variables

  1. Variables are used to declare a certain memory block in memory to be used by the program
  2. The data in this area can be constantly changing within the same type range
  3. 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
  4. Variables in java must be declared before use
  5. Use variable names to access data in this area
  6. The scope of the variable: within the pair {} where it is defined
  7. Variables are only valid within their scope
  8. 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)

  1. Different locations: local variables are written in methods; member variables are written directly in classes
  2. The default values ​​are different: member variables have default values; local variables have no default values, and must be assigned before they are used.
  3. Different scope: local variables are only valid in methods; member variables are valid in all methods
  4. Access modifiers are different: local variables cannot use access modifiers; member variables can use access modifiers
  5. 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

  1. Literal constant: is the literal meaning, such as: 123, "ABC", "中", etc.
  2. 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;
	}
}

Guess you like

Origin blog.csdn.net/qwy715229258163/article/details/113704624