Constant: If its value remains unchanged, it is a constant.
grammar:
Data type constant name = value;
double PI = 3.14;
Remark:
Generally, the default constant name is capitalized.
Relationship between variables and constants (relationship between quantities)
Let’s first take a simple example to understand the relationship between variables and constants in Java.
The following program declares two variables that are often used in Java, namely the integer variable num and the character variable ch. After assigning values to them, display their values on the console separately:
The following program declares two variables, one is an integer and the other is a character type
public class TestJava{ public static void main(String args[]){ int num = 3 ; // Declare an integer variable num, assign a value of 3 char ch = 'z'; // Declare a character variable ch, assign a value of z System.out.println(num+ "is an integer!"); // Output the value of num System.out.println(ch + "is a character!"); // Output the value of ch} }Output result:
3 is an integer!
z is a character!
illustrate:
Two different types of variables num and ch are declared, and the constant 3 and character "z" are assigned to these two variables respectively, and finally they are displayed on the display. When declaring a variable, the compiler will open up a piece of memory space in memory that can accommodate this variable. Regardless of how the value of the variable changes, the same memory space is always used. Therefore, making good use of variables will be a way to save memory.
A constant is a type different from a variable, and its value is fixed, such as integer constants and string constants. Usually when a variable is assigned, the constant will be assigned to it. In the program TestJava, line 6 num is an integer variable, and 3 is a constant. The purpose of this line is to declare num as an integer variable and assign the value of constant 3 to it.
Similarly, line 7 declares a character variable ch and assigns the character constant 'z' to it. Of course, during the process of the program, you can reassign the variables, or use the declared variables.
Thank you for reading, I hope it can help you. Thank you for your support for this site!