Java数据类型转换
2016-07-29 17:52
387 查看
类型的转换
自动转换
如果数字运算都是以int去处理,但是如果有一个数字是long,就会转换成long
byte和short都会以int类型去运算
byte short -->int
int long -->long
byte short int long -->long
强制转换
(数据类型)
如果浮点数转成整型 直接把小数点后面的全部去掉,没有四舍五入
强转的时候默认强转紧跟在后面的变量,如果需要强转整个那就把要强转的括起来
double d = 12.5;
int a = (int)d;
float 的存储的数据范围 大于 long
public class Test01Calc{
public static void main(String[] args){
//同类型的运算
int i1 = 9/5;
double d1 = 9.0/5;
//将来做int/int计算的时候,如果要保留小数,可以提前*1.0
double d2 = 81*1.0/20;
//byte b1 = 1;
//b1 = b1+1;
//b1++;
byte b1 = 1;
byte b2 = 1;
//也会丢失精度
byte b3 = (byte)(b1+b2);
System.out.println(b3);
int i2 = 100;
float f2 = i2+1.0f;
float f3 = 100.0f;
int i3 = (int)f3+1;
long l4 = 21000000000L;
float f4 = l4+1.0f;
double d5 = 12.8;
int i5 = (int)d5;
double d6 = Math.random();
int score = (int)(d6*101);
System.out.println(score);
}
}
自动转换
如果数字运算都是以int去处理,但是如果有一个数字是long,就会转换成long
byte和short都会以int类型去运算
byte short -->int
int long -->long
byte short int long -->long
强制转换
(数据类型)
如果浮点数转成整型 直接把小数点后面的全部去掉,没有四舍五入
强转的时候默认强转紧跟在后面的变量,如果需要强转整个那就把要强转的括起来
double d = 12.5;
int a = (int)d;
float 的存储的数据范围 大于 long
public class Test01Calc{
public static void main(String[] args){
//同类型的运算
int i1 = 9/5;
double d1 = 9.0/5;
//将来做int/int计算的时候,如果要保留小数,可以提前*1.0
double d2 = 81*1.0/20;
//byte b1 = 1;
//b1 = b1+1;
//b1++;
byte b1 = 1;
byte b2 = 1;
//也会丢失精度
byte b3 = (byte)(b1+b2);
System.out.println(b3);
int i2 = 100;
float f2 = i2+1.0f;
float f3 = 100.0f;
int i3 = (int)f3+1;
long l4 = 21000000000L;
float f4 = l4+1.0f;
double d5 = 12.8;
int i5 = (int)d5;
double d6 = Math.random();
int score = (int)(d6*101);
System.out.println(score);
}
}
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序