The differences between Java constants and variables are described in detail

  • 2020-05-10 18:05:44
  • OfStack

            constant: a constant whose value does not change.

Grammar:

Data type constant name = value;

double PI = 3.14;

Remark:

The default constant name is uppercase.

Relationship between variables and constants (relationship between quantities)

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, the integer variable num and the character variable ch. After assigning values to them, display their values on the console:

The following program declares two variables, one integer and one character


 public class TestJava{

  public static void main(String args[]){

  int num = 3 ; //  The statement 1 Integer variables  num For, an assignment  3

  char ch = 'z'; //  The statement 1 Character variables  ch For, an assignment  z

  System.out.println(num+ " Is an integer. "); //  The output  num  The value of the 

  System.out.println(ch + " Is character! "); //  The output  ch  The value of the 

  }

  }

Output results:

Three 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 them, respectively, before they are displayed on the display. When a variable is declared, the compiler gives it a chunk of memory large enough to hold it. Always use the same memory space no matter how the value of the variable changes. Therefore, making good use of variables will be a way to save memory.

A constant is a type that is different from a variable and has a fixed value, such as an integer constant or a string constant. Normally when you assign a value to a variable, you assign a constant to it. In 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 it the value of the constant 3.

Similarly, line 7 declares the 1-character variable ch and assigns the character constant 'z' to it. Of course, you can reassign variables as the program progresses, or you can use variables that have already been declared.

            thanks for reading, hope to help you, thank you for your support of this site!


Related articles: