java基础03
类型转换
- Java是强类型语言,所以要进行有些运算的时候需要进行类型转换
- 容量从低到高byte,short,char<int<long<float<double
- 运算中不同类型的数据要先转换成同一类型,然后进行运算
- 转换时要注意内存溢出,例如(此处使用了强制转换,强制转换的格式就是:(类型)变量名):
public class hello {
public static void main(String[] args) {
int i = 128;
byte b = (byte)i;
System.out.println(i);
System.out.println(b);
}
}
输出结果为:
128
-128
Process finished with exit code 0
为什么会是-128?
public final class Byte extends Number implements Comparable<Byte> {
/**
* A constant holding the minimum value a {@code byte} can
* have, -2<sup>7</sup>.
*/
public static final byte MIN_VALUE = -128;
/**
* A constant holding the maximum value a {@code byte} can
* have, 2<sup>7</sup>-1.
*/
public static final byte MAX_VALUE = 127;
因为byte对应的Byte类的最大值为127,128内存已经溢出了类型转换时,一定要注意不能溢出
- 强制转换格式为:(类型)变量名,同时强制转换是由高到低的转换
- 自由转换不需要任何操作,是由低到高的转换,如:
public class hello {
public static void main(String[] args) {
int i = 128;
double b = i;
System.out.println(i);
System.out.println(b);
}
}
输出结果为:
128
128.0
Process finished with exit code 0
- 要注意不能对布尔值进行转换,不能把对象类型转换成不相干的类型
- 转换的时候可能会存在内存溢出或者精度问题,如:
public class hello {
public static void main(String[] args) {
System.out.println((int)68.5);
System.out.println((int)46.468f);
}
}
输出结果为:
68
46
Process finished with exit code 0
同时字符本质也是数字,是否也可以进行转换?例:
public class hello {
public static void main(String[] args) {
char c = 'a';
int i = c+1;
System.out.println(i);
//强制转换回char
System.out.println((char)i);
}
}
输出结果为:
98
b
Process finished with exit code 0
- 操作较大或较多数字时容易溢出,应如何处理?例:
public class hello {
public static void main(String[] args) {
int c = 100;
int y = 365;
int h = 24;
int m = 60;
int s = 60;
System.out.println(c*y*h*m*s);
}
}
输出结果为:
-1141367296
Process finished with exit code 0
很明显数据已经溢出,如何解决?
public class hello {
public static void main(String[] args) {
int c = 100;
int y = 365;
int h = 24;
int m = 60;
int s = 60;
System.out.println(c*y*h*m*s);
//定义成long是否可行?
long l = c*y*h*m*s;
System.out.println(l);//输出结果依旧未变,因为默认是int类型,转换前已经出问题了
//正解
long L = ((long)c)*y*h*m*s;
System.out.println(L);
}
}
输出结果:
-1141367296
-1141367296
3153600000
Process finished with exit code 0
要在计算时先把一个数转换为long,整体就会升为long类型
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现