基本数据类型
- 不能对boolean类型进行类型转换。
- 不能把对象类型转换成不相关类的对象。
- 在把容量大的类型转换为容量小的类型时必须使用强制类型转换。
- 转换过程中可能导致溢出或损失精度,例如:
int i =128;
byte b = (byte)i;
因为 byte 类型是 8 位,最大值为127,所以当 int 强制转换为 byte 类型时,值 128 时候就会导致溢出。
- 浮点数到整数的转换是通过舍弃小数得到,而不是四舍五入,例如:
(int)23.7 == 23;
(int)-45.89f == -45
字节是程序进行操作的最小单元。别的数据类型都是在他的基础上描述,char 2字节,short 2字节,int 4 字节 …
字节自动转为别的基本类型,但强转为 char
public static void main(String[] args) {
byte by = 120;
char cr = (char) by;
short st = by;
int it = by;
long lg = by;
float ft = by;
double db = by;
System.out.println(cr);
System.out.println(st);
System.out.println(it);
System.out.println(lg);
System.out.println(ft);
System.out.println(db);
}
发现,别的都是自动转,到了 char 就是强转,要不编译报错。
因为字节变为字符需要解码,字符变为字节需要编码。
Number 类
抽象类Number是平台类的超类,表示可转换为基本类型byte 、 double 、 float 、 int 、 long和short数值。
Byte
public final class Byte extends Number implements Comparable<Byte>
Short
public final class Short extends Number implements Comparable<Short>
Integer、Long、Float、Double 这几个都这样
貌似没有 char ,但是发现几乎每个都有与 String 进行交互的,而且还不止一个。
String的源码中,不就是用 char [] 存储和操作的么
String:
这里也有很多根据基本类型,生成 String 的。
这些个都命名为 valueOf ()
字节数组、 char 数组 互转
- 循环遍历强转。
- 和String发生关系,进行转换
public class Test {
public static void main(String[] args) {
byte[] bytes = {112, 115, 120};
char[] chars = new char[bytes.length];
for (int i = 0; i < bytes.length; i++) {
chars[i] = (char) bytes[i];
}
System.out.println(chars);
}
}
public class Test {
public static void main(String[] args) {
byte[] bytes = {112, 115, 120};
char[] chars = new char[bytes.length];
String s = new String(bytes);
s.getChars(0, bytes.length, chars, 0);
System.out.println(chars);
}
}
还是循环遍历顺眼点。
反正,如果遇到和 String 或 char 相关的就去看看 String 是否已经提供了。
遇到和数组相关的就去看看 Arrays ,根本没有必要专门记。