Talk about constants and variables

What are constants and variables

Constant: the amount that the program will not change during operation is called a constant.

Variable: the amount that will change during the operation of the program is called variable.

Declaration of variables:

In Java, declaring a variable requires the following three elements: variable name, variable type and scope.

The variable name is very simple, as long as it is not a Java keyword, but it is usually the habit of programmers to use the English corresponding to the meaning of variables, which is also an unwritten rule.

Variable types include basic data type and reference type.

Basic data types (4 types and 8 types)

Integer type: byte short int long (different types represent different lengths)

Byte: uses one byte storage, so the range is - 128-127

Short: uses two bytes to store, so the range is - 32768-32767

Int: uses four bytes to store, so the range is plus or minus 2.1 billion

Long: uses eight bytes of storage, so the range is......

Note:

1. When integer types are used, they are all int types by default,

2. If you need to use long type, you must add L after the number. It is recommended to use uppercase, which is easy to be confused with 1.

Floating point type: float double decimal type: use decimal point and scientific counting method

Float: single precision. The precision can be accurate to 7 decimal places

Double: double precision. The precision is twice that of float

Note:

1. The default floating point type is double

2. When using float, add f after the number

3. Floating point type cannot represent an exact value, which will lose some precision

Character type: char

It takes up 2 bytes and is represented by ''

Boolean type: Boolean

There are only two values: true and false, which occupy one bit when stored

Reference data type: (class, interface, array)

Scope: declared in the class, variables outside the method define member variables, and there are default values for the whole class.

Variables declared in the method are defined as local variables. Local variables must be initialized. There is no default value. If they are used without initialization, compilation errors will occur.

For example, the following code:

If only one string variable STR is defined, but there is no assignment, the compiler will report red directly.

Declaration of constants:

Variables modified with the final keyword are called constants or final constants, indicating that they cannot be modified.

In addition, variables modified by static + final are called static constants. Static and final are two very important keywords in Java. These two keywords will be summarized separately in subsequent articles.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>