day02-数据类型转换_概述和自动转换

This commit is contained in:
2026-04-19 15:50:14 +08:00
parent afa330c8b0
commit 3a9a5988eb
2 changed files with 55 additions and 0 deletions

View File

@@ -0,0 +1,34 @@
package com.inmind.type_cast01;
/*
Java程序中要求参与的计算的数据必须要保证数据类型的一致性如果数据类型不一致将发生类型的转换
数据类型转换---自动转换
自动转换:将取值范围小的类型(byte)自动提升为取值范围大的类型(int)
---------------------------------------------
转换顺序:byte、short、char---->int---->long---->float---->double
*/
public class Demo01 {
public static void main(String[] args) {
//定义一个整数
int a = 10;
int b = 20;
//计算两个变量的和
int c = a+b;
//定义字节类型
byte b1 = 2;
int result = b+b1;//发生了自动类型转换b1自动提升为int
System.out.println(result);//22
//-------------------------------------------------------
byte b3 = 10;
byte b4 = 20;
//byte val = b3+b4;//错误因为byte+byte结果会超出byte的范围在java中byteshortchar进行运算都会先提升为int来计算
int val = b3+b4;
System.out.println(val);
//-----------------------------------------
int s = b3+b4;
System.out.println(s);
}
}

View File

@@ -0,0 +1,21 @@
package com.inmind.type_cast01;
/*
自动转换的举例和顺序
转换顺序:byte、short、char---->int---->long---->float---->double
*/
public class Demo02 {
public static void main(String[] args) {
byte b = 10;
short s = b;//只要是byteshortchar进行运算必定先提升为int计算
char c = 'a';
int a = c;
int i = s;//自动类型提升
long l = i;
float f = l;
double d = f;
}
}