type conversion in java

Today, I reviewed the basics of java and reviewed the type conversion in java.

1. Automatic type conversion

Numerical types in java can be automatically converted, which means that a small range can be automatically converted to a large range.

In general, the picture is as follows:

Another automatic conversion is that when any basic type is concatenated with a string, the value of the basic type will be automatically converted to a string type.

E.g:

String c=1+"2";

The value 1 is automatically converted to the string "1" and then concatenated with the string "2".

But beware:

String c1=3+4+"hello";// c1=7hello
string c3="hello"+3+4;//c2=hello34

 The connection operator "+" is calculated from right to left. In c1, 3 is first added 4 to become 7, 7 and then connected with "hello". In c3, "hello" is first connected to 3 to form "hello3" and then to 4 to form "hello34"

 

2. Forced type conversion

The basic syntax is (type)value, which forces the value to be converted to type.

Mainly because the data range represented by the value type is larger than the type type, and forced conversion will cause data loss.

There is also a coercion that converts string to basic data type. Normally we cannot convert string type to primitive data type. But it can be achieved by a wrapper class of the basic type

For example: int c = Integer.parseInt("34")

3. Automatic upgrade of expression types

The entire arithmetic expression data type is automatically promoted to the same level as the highest-level operand of the expression. An easy mistake to make when writing code in the past:

short val=5;
val=val+2;

The expression operation level of val=val+2 will automatically increase the int that is the same size as 2, and an error will be reported when int is assigned to short

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324847134&siteId=291194637