day02-数据类型转换_概述和自动转换
This commit is contained in:
34
day02/src/com/inmind/type_cast01/Demo01.java
Normal file
34
day02/src/com/inmind/type_cast01/Demo01.java
Normal 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中,byte,short,char进行运算,都会先提升为int来计算
|
||||||
|
int val = b3+b4;
|
||||||
|
System.out.println(val);
|
||||||
|
//-----------------------------------------
|
||||||
|
int s = b3+b4;
|
||||||
|
System.out.println(s);
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
21
day02/src/com/inmind/type_cast01/Demo02.java
Normal file
21
day02/src/com/inmind/type_cast01/Demo02.java
Normal 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;//只要是byte,short,char进行运算,必定先提升为int计算
|
||||||
|
char c = 'a';
|
||||||
|
int a = c;
|
||||||
|
int i = s;//自动类型提升
|
||||||
|
|
||||||
|
long l = i;
|
||||||
|
|
||||||
|
float f = l;
|
||||||
|
double d = f;
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user