JavaSE base (x) - the basic data type conversion in Java

Basic data type conversion in Java

 

Before said basic data type conversion, to understand the eight basic data types in Java, and their total memory capacity and the size range indicated, as shown in FIG.

 

image

 

Re ponder the primitive data types, it is now converted to explain the relationship between them.

 

Automatic type conversion

 

Automatic type conversion means: small numerical data type can be automatically converted into a wide range of data types.

 

Such as:

 

long l = 100;
int i = 200;
long ll = i;

 

As shown particularly in FIG automatically converted as follows.

 

image

 

The solid line represents no data loss when automatic conversion, the dotted line may occur data loss problems.

 

Automatic conversion of data overflow problems have to be careful, look at the following example.

 

int count = 100000000;
int price = 1999;
long totalPrice = count * price;

 

Compile without any problems, but the result output is negative, because the result is obtained by multiplying two int int, the result of multiplying beyond the scope of representation of int. This case, typically convert a wide range of data into a first data type and other data for re-calculation.

 

int count = 100000000;
int price = 1999;
long totalPrice = (long) count * price;

 

Further, when down-converting int constant can be directly assigned to the literal byte, short, char and other types of data, without the need for cast, as long as the constant value does not exceed the range of the type of representation can be automatically converted.

 

Cast

 

Cast we know only too well that the forced display to convert a data type to another data type.

 

Such as:

 

short s = 199;
int i = s;// 199

double d = 10.24; long ll = (long) d;// 10

 

Above conversion results are within our expectations, the situation is normal conversion and loss of accuracy, the following examples belong to the same data overflow situation.

 

int ii = 300;
byte b = (byte)ii;

 

300 byte beyond the scope of the type represented, it will be converted into a digital meaningless.

 

Type promotion

 

The so-called type promotion refers to data in a variety of different types of expressions, the type is automatically indicated to a large value range of the data type of upgrade.

 

Examples of the above overflow and then change the next.

 

long count = 100000000;
int price = 1999;
long totalPrice = price * count;

 

price is int type, count as long type, long type result of the operation, the result of normal operation, overflow does not occur.

 

 

Guess you like

Origin www.cnblogs.com/fzsz086/p/11964666.html