Java basic syntax: type conversion


  • Because Java is a strongly typed language, it is sometimes used in operationsType conversion

  • Integer, constant and character type data can be mixed.

  • In operation,Different types of data are converted to the same type first, and then perform the operation.

  • The type conversion level can be divided from low level to high level, mainly according toMemory capacity of data typeTo divide,The larger the capacity, the higher the level, andFloating point type has higher priority than integer type

  • When a low-level data type is converted to a high-level data type, theAutomatic type conversion

  • When a high-level data type is converted to a low-level data type, it must beCast type

Type conversion level:

/*Low level ----------------------------------------------- high level*/
/* byte -> short,char -> int -> long -> float -> double */

Type conversion rule:

  1. Cannot type convert boolean type.
  2. You cannot convert an object type to an object of an unrelated class.
  3. Cast must be used when converting a high-level type to a low-level type.
  4. Automatic type conversion cannot be performed between byte type to char type, short type and char type.

1、 Automatic type conversion

  • Basic data types with small numerical range can be automatically converted to basic data types with large numerical range.

be careful:

  1. Automatic type conversion cannot be performed when byte type is converted to char type.
  2. Short type and char type are converted to each other, and automatic type conversion is not allowed.
  3. When char type is converted to a higher level type, automatic type conversion can be performed.


byte byteNumber = (byte)1;
short shortNumber = byteNumber;
char charNumber = (char) shortNumber;
int intNumber = charNumber;
long longNumber = intNumber;
float floatNumber = longNumber;
double doubleNumber = floatNumber;

2、 Cast type

  • Used to explicitly convert a numeric type. The converted data type must be compatible.

Syntax:‘(‘ + type + ‘)’ + value




be careful:Cast may causeoverfloworLoss accuracyFor example:

/*Because the memory capacity of byte type is 8 bits and the maximum value is 127, when the value 128 of int type is cast to byte type, overflow will be caused*/
System.out.println((byte) 128);//-128
/*The conversion from floating-point number to integer is obtained by discarding decimals rather than rounding, so precision will be lost*/
System.out.println((int) 99.9);//99
System.out.println((int) -99.99f);//-99

Recommended Today


Supervisor [note] Supervisor – H view supervisor command help Supervisorctl – H view supervisorctl command help Supervisorctl help view the action command of supervisorctl Supervisorctl help any action to view the use of this action 1. Introduction Supervisor is a process control system. Generally speaking, it can monitor your process. If the process exits abnormally, […]