constants: Constants with values unchanged.
Grammar:
Data type constant name = value;
Double PI = 3.14;
Note:
The general default constant name is uppercase.
Relationship between variables and constants (quantity relationship)
Let's start with a simple example to understand the relationship between variables and constants in Java.
The following program declares two variables commonly used by Java, integer variable num and character variable ch. Assign values to them, and then display their values on the console separately:
The following program declares two variables, one is an integral type, 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 C h = ' Z '; Declares a character variable ch, assigned to Z
System.out.println (num+) is an integer! "); Output num value
System.out.println (ch + "is the character!) "); Output ch value
}
}
Output results:
3 is an integer!
Z is the character!
Description
Two different types of variables num and CH are declared, and the constant 3 and the character "Z" are assigned to the two variables, which are then displayed on the monitor. When you declare a variable, the compiler opens up a memory space in memory that is sufficient to hold the variable. The same memory space is always used regardless of how the value of the variable changes. Therefore, the 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 an integer constant, a string constant. When a variable is usually assigned a value, the constant is assigned to it, and in the program Testjava, line 6th is an integer variable, and 3 is a constant. The purpose of this row is to declare num as an integer variable and assign the value of constant 3 to it.
Similarly, Line 7th declares a character variable ch and assigns the word constants quantity ' Z ' to it. Of course, in the course of the program, you can assign a value to a variable, or you can use a variable that has already been declared.
Thank you for reading, I hope to help you, thank you for your support for this site!