JAVA数据类型的转换

数据类型转换

数据类型转换有隐式转换和显示转换2种。

一般大数据类型能容纳小数据类型的内容,因此系统提供了隐式转换。

"="是java里面的赋值运算符,它的功能是把=右边的值,赋值给左边的变量。

byte a1 = 100;  
short b1 = a1;  
int c1 = b1;  
long d1 = c1;

一、大类型往小类型转换就出现编译错误。如果非要转换,可以使用强制类型转换。(整数默认类型是int)

short a1 = 100; 
byte b1 = (byte)a1;  
System.out.println(b1);
int c1 = 200;
byte b2 = (byte)c1; 
System.out.println(b2); 
byte a10 = 5; 
a10 = (byte)(a10 + 1); 
System.out.println(a10); 
byte b10 = 5; 
short c10 = 6;
c10 = (short)(b10 + c10);  
System.out.println(c10);
byte b10 = 5; 
short c10 = 6;
c10 = (short)(b10 + c10);
System.out.println(c10); 
byte b10 = 5; 
short c10 = 6; 
int d10 = b10+c10;
System.out.println(d10);

二、类型转换 float + int结果是float

int x = 100;
float y = 12.5f;
int z = (int)(x + y);                       
System.out.println(z);    
int x = 100;
float y = 12.5f;
float w = x + y;
System.out.println(w);
long x = 100;
float y = 1.25f;
long z = (long)(x + y);                 
System.out.println(z);                 
long x = 100;
float y = 1.25f;
float w = x + y;
System.out.println(w);

三、字符类型运算

char c10 = 'a';
char d10 = (char)(c10 + 3);
int e10 = c10 + 3;
System.out.println(e10);  (结果:100)
System.out.println(d10);  (结果:d)

四、布尔类型只表示真假,不能参与运算,不能与其他类型互转,包括强转。

例如:

boolean h10 = true;   
boolean h11 = false;

五、总结:

隐式转换:小转大,大类型可以接收小类型。

赋值时:小类型可以赋值给大类型。byte->short->int->long->float->double; char->int->long->float->double

运算时:

  • 小于等于int类型的整数进行运算,会自动升级为int,再进行运算。
  • 小于等于long类型整数与long进行运算,会自动升级为long,再进行运算。
  • 如果和float运算,升级为float,再进行运算。
  • 如果和double运算,升级为double,再进行运算。
  • 如果=左边的变量类型小于=右边的类型,要进行强制转换。 强制转换格式: 变量 = (指定的类型)数值,指定的类型要与变量的类型一致。

查阅八种基本数据类型点击此处

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值