In Java programs, it is often necessary to convert data between different basic data types. For example:
,
The int variable score1 in the code can perform the assignment directly for the double type variable score2, with the result of: 82.0
This conversion is called automatic type conversion.
Of course automatic type conversions are required to meet specific conditions:
1. The target type can be compatible with the source type, such as type double compatible int, but char type cannot be compatible with int
2. The target type is greater than the source type, such as the double type is 8 bytes long, the int type is 4 bytes, so the double type of the variable can directly hold the int type of data, but the reverse is not possible
Automatic type conversion rules:
To force type conversions:
code example:
1 Packagecom.jredu.ch02;2 3 Public classCh04 {4 5 Public Static voidMain (String[]args) {6 //Automatic type conversion7 //automatic type conversion of basic data has only 7 data types except the Boolean8 //basic principle: Low level can be directly higher level9 //CharTen //byte->short->int->long->float->double One //automatic conversion conditions for the operation: 1, two data types to be compatible, 2, the target type is greater than the original type A inta=10; - Doubleb=1.1; -b=b+A; theA=a+ (int) b; -System.out.println (b);//b=11.1 -System.out.println (a);//a=10+11=21 - + } - +}
1 Packagecom.jredu.ch02;2 3 Public classCh05 {4 5 Public Static voidMain (string[] args) {6 //TODO auto-generated Method Stub7 //Forcing type conversions8 //high-level turn low, you must have a strong turn9 //whether the cast depends on the level of the data type does not depend on the actual value of the data. Ten inta=330; One ShortB= ( Short) A; A Shortc=350;//Direct argument assignment, no conversion type required - - intE= (int)-1.1; theSystem.out.print (e);//E=-1 - - - } + -}
Type conversions in Java