java数据类型转换
语法:
A.自动类型转换:在某种条件下,系统自动完成类型转换也称隐含转换(Implicit casting)
a.两种类型兼容
b.目标类型大于源类型
c.对于表达式,如果一个操作数为double型,则整个表达式可提升为double型
B.强制类型转换(Explicit Casting):在一定条件下,程序员手动完成类型转换
a.两种类型兼容
b.一般目标类型小鱼源类型
要点:1.强制类型转换会丢失精度
示例:1.自动类型转换:
int i = 10;
double d = i;
2.强制类型转换:
double d = 10.0;
int i = (int)d;
示例代码:
1 package com.sanlianxueuan; 2 3 public class Demo03 { 4 5 /** 6 * 数据类型的转换 7 */ 8 public static void main(String[] args) { 9 //自动类型转换(隐式转换) 10 byte num1 = 10; 11 int num2 = num1; 12 System.out.println(num2); 13 long num3 = num2; 14 System.out.println(num3); 15 16 float f = 10.5f; 17 double d = f; 18 System.out.println(d); 19 20 int num4 = 100; 21 float num5 = num4; 22 System.out.println(num5); 23 24 char c1='a'; 25 int num6 = c1; //字符赋值给整形变量 26 System.out.println(num6); 27 System.out.println(c1+10); 28 System.out.println((char)(c1+10)); 29 30 31 //强制类型转换(显式转换) 32 int num7 = 10; 33 short num8 = (short) num7; 34 System.out.println(num8); 35 36 float num9 = (float) 10.25; 37 System.out.println(num9); 38 39 int num10 = 65; 40 char num11 = (char)num10; 41 System.out.println(num11); 42 43 int num12 = 10; 44 double num13 =10.6; 45 float res = (float) (num12+num13); 46 System.out.println(res); 47 48 /*总结:byte<short(char)<int<long<float<double*/ 49 50 } 51 52 }