public class TestDataType {
public static void main(String[] args) {
//byte,short,int ,long都可以用十进制、8进制,16进制。前缀0表示8进制,前缀0x表示16进制
testType();
stringCharTest();
floatDoubleTest();
automaticTypeTransform();
}
public static void testType() {
int decimal = 100;
int octal = 0144;
int hh = 0x64;
System.out.println(decimal + "----" + octal + "------" + hh);
byte a = 16;
byte b = 020;
byte c = 0x10;
System.out.println(a + "--" + b + "---" + c + "--");
short x = 16;
short y = 020;
short z = 0x10;
System.out.println(x + "--" + y + "---" + z + "--");
long e = 16;
long f = 020;
long g = 0x10;
System.out.println(e + "--" + f + "---" + g + "--");
}
public static void stringCharTest() {
char c = '\u0001';
String a = "\u0001";
System.out.println(c + "---" + a);
String b = "\\";
char b1 = '\\';
char d1 = '\'';
String d = "\'";
String x1 = "\t";
char x = '\t';
System.out.println(b + "--" + b1 + "---" + d1 + "--" + d + " " + x1 + "--" + x);
}
public static void automaticTypeTransform() {
//不能对boolean类型进行类型转换
boolean f = true;
Integer a = 1;
String s = String.valueOf(a);
//自动转换 是 byte,short,char->int->long->float->double,反过来需要强制类型转换
char c1 = 'a';
int i1 = c1;
System.out.println("char自动类型转换为int后的值等于:" + i1);
char c2 = 'A';
int i2 = c2 + 1;
System.out.println("char自动类型转换为int后的值等于:" + i2);
int c = 2;
long d = c;
System.out.println("int自动类型转换为long后的值等于:" + d);
char s1 = (char) c;
System.out.println("int类型强制转换为char类型的值:" + s1);
byte b1 = (byte) c;
System.out.println("int类型强制转换为byte类型的值为:" + b1);
//转换过程中可能会导致溢出或损失精度,因为byte类型是8未,最大值是127,当int型的i强制转换为byte类型时,值128就会导致溢出
int i = 128;
byte j = (byte) i;
System.out.println(" int类型的i的值 " + i + "int类型的i强制转换为byte型的j 出现内存溢出 " + j);
}
public static void floatDoubleTest() {
//浮点类型转换为整数是通过舍弃小数得到,而不是四舍五入
float f = -45.79f;
double d = 25.6;
int a = (int) f;
int b = (int) d;
System.out.println(a + " " + b);
}
}
输出结果