Java Variable and constant


Variable

In programming, a variable is a carrier that stores data. The variables in the computer are the actual data, and there is an essential difference between the abstract "variable" in the mathematical equation. The value of a variable can be read and modified, which is the basis for all calculations.


Variable statement

How do I use a variable? First you need to create a variable by giving it a unique and legal name.

The basic way to declare a variable:

[data type] [variable name];
[data type] [variable name] = [value or expression];

There are also some ways to declare variables at the same time, which will be described later.

In front of the introduction of the int, char, float and several basic data types, they can be used to create basic variables.

Variable names need to adhere to the following specifications :

  • Must begin with a letter, an underscore, or a dollar sign
  • Only letters, underscores, numbers and dollar signs, no other symbols or spaces
  • You can not use reserved words as names
  • Within the same scope of use, the names of all variables, functions, classes, objects, etc., must not be repeated

Variable names may consist of meaningless words, and variable names are subject to a lot of restrictions. A variable name that conforms to the above specification can be accepted by the compiler, but it does not mean that the variable name that satisfies the above requirements is "acceptable". In order to be able to make themselves and others more clearly understand the program, variable name also need to meet other specifications.

See the next section, Java / Programming Specification.


Variable type conversion

Each variable has its own type, which is usually not changed. But many times the data of different data types to be put together to calculate, or a method requires the data type and the variable does not match, which requires type conversion.

From low precision to high precision can be directly converted, such as int → float → double

int num1 = 12;
float num2 = num1;
double num3 = num2;

And vice versa to use the mandatory type conversion:

double num1 = 12.1;
float num2 = (float) num1;
int num3 = (int) num2;

Constant

Constant means the value that can not be changed. In the final logo in Java, the statement and the variable similar to:

public static final double PI = 3.1415927;

Although constant names can also be used in lower case, but in order to facilitate identification, usually using capital letters that constant.




Copyright 2014-2017 by DeveloperTut.com. All Rights Reserved.
TwitterGoogle+Facebook