第二天内容比较多,而且内容重点也有所不同,故分两篇发送
附原视频地址:【零基础 快速学Java】韩顺平 零基础30天学会Java_哔哩哔哩_bilibili
Java基础-数据类型转换
基本数据类型转换
自动类型转换
- 当java程序在进行赋值或者运算时,精度小的类型自动转换为精度大的数据类型,这个就是自动类型转换
示例代码(看不明白可以往下看细节的代码)
class test1{
public static void main(String[] args){
int num = 'a';
double d1 = 80;
System.out.println(num);
System.out.println(d1);
}
}
>97
>80.0
自动类型转换注意和细节
-
有多种类型的数据混合运算时,系统首先自动将所有数据转换成容量最大的那种数据类型,然后再进行计算。
class test1{ public static void main(String[] args){ int n1 = 10; //正常赋值 //float d1 = n1 + 1.1; 会报错,1.1是double double d1 = n1 + 1.1; //正常 float d1 = n1 + 1.1F;//正常,将1.1转成float,此时最大是float } }
-
当我们把精度(容量)大的数据类型赋值给精度(容量)小 的数据类型时,就会报错,反之就会进行自动类型转换。
class test1{ public static void main(String[] args){ int n1 = 1.1; //报错 byte b1 = 10; //正确,在byte范围内 /** int n2 = 1; byte b2 = n2; 报错,变量赋值不行;想象一下存储空间已经申请了四个字节,然后又放到一个1字节的,会丢失精度,即使在范围内 */ } }
-
根据最上图的转换链路(byte,short)和char之间不会相互自动转换(规则)
-
byte,short 和 char,三者可以进行计算,需要计算前转换为int类型 (谨记只要有一个出现运算中,他们都会自动转换成int类型)
-
boolean类型不参与转换
强制类型转换
-
自动类型转换的逆过程,将容量大的数据类型转换为容量小的数据类型。使用时要加上强制转换符(),但可能造成精度降低或溢出,格外要注意。
class test1{ public static void main(String[] args){ int n1 = (int)1.9;//正常情况过不去,但是用了强制转换 System.out.println("n1=" + n1); int n2 = 2000; byte b1 = (byte)n2; //byte范围-128~127,溢出 System.out.println("b1=" + b1); } } >n1=1 >b1=-48
强制转换类型转换注意和细节
-
当进行数据的大小从大---->小,就需要使用到强制转换
-
强转符号只针对于最近的操作数有效(其实就是优先级问题)
class test1{ public static void main(String[] args){ //int x = (int)10 * 3.5 + 5 / 1.7; 会报错,精度错误 int x = (int)(10 * 3.5 + 5 / 1.7);//正常 System.out.println("x=" + x); } } >37
-
char类型可以保存int的常量值,但不能保存int的变量值,需要强转
class test1{ public static void main(String[] args){ char c1 = 100; int i1 = 100; //char c2 = i1; 报错,变量不行 char c3 = (char)i1; //这个100值 常量可以 System.out.println(c3); //100的对应字符 } } >d
-
byte和short,char类型在进行运算时,当作int类型处理。
-
基本数据类型和String类型的转换
基本转string
class test1{
public static void main(String[] args){
int n1 = 100;
float f1 = 1.1F;
double d1 = 4.3;
boolean b1 = true;
String s1 = n1 + "";
String s2 = f1 + "";
String s3 = d1 + "";
String s4 = b1 + "";
System.out.println(s1 + " " + s2 + " " + s3 + " " + s4);
}
}
>100 1.1 4.3 true
string转基本
class test1{
public static void main(String[] args){
String s1 = "123";
int num1 = Integer.parseInt(s1);
double num2 = Double.parseDouble(s1);
float num3 = Float.parseFloat(s1);
long num4 = Long.parseLong(s1);
byte num5 = Byte.parseByte(s1);
boolean b = Boolean.parseBoolean(s1);
short num6 = Short.parseShort(s1);
//用到的是基本数据类型对应的包装类,进行转换
//字符串转成char的话,是截取串中的一个字符的方式,不是真正意义上的转
System.out.println(s1.charAt(0));//去123中下标为0的,也就是'1'这个字符
}
}
Detail
- 在将String 类型转成 基本数据类型时,要确保String类型能够转成有效的数据,比如 我们可以把“123"转成一个整数,但是不能把"hello" 转成一个整数
- 如果格式不正确,就会抛出异常,程序就会终止,这个问题在异常处理章节中,会处理