1.数据类型
2.基本数据类型转换
(1) 自动类型转换 (隐式转换)
表示从范围小的类型转换为范围大的类型,可以直接转换,称为隐式转换.
short a = 10;
int b = a; //自动类型转换, a 是 short 类型, 自动转换为 int 类型
(2) 强制转换类型 (显式转换)
表示从范围大的类型转换为范围小的类型,会造成精度损失,需要强制转换,称为显式转换.
强制类型转换的语法格式就是 加一个括号, 然后给出想要转换的目标类型.
转换规则为: a = (a的数据类型)b。
double a = 3.14;
int b = (int)a;
3.包装类型
基本类型都有对应的包装类型,基本类型与其对应的包装类型之间的赋值通过自动拆箱和自动装箱完成,
Integer a = 6; // 装箱 调用了 a.valueOf(6);
int b = a; // 拆箱 调用了 a.IntValue();
4.数据缓存池
new Integer(127) 与 Integer.valueOf(127) 的区别在于:
(1) new Integer(127) 每次会新建一个对象;
(2) Integer.valueOf(127) 会使用缓存池中的对象, 每次会调用同一个对象的引用.
Integer i1 = new Integer(127);
Integer i2 = new Integer(127);
System.out.println(i1==i2); //false
Integer i3 = 127;
integer i4 = 127;
System.out.println(i3==i4); //true
输出结果不同是应为自动装箱是调用的Integer的valueOf方法,通过查看其源码:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
当符合i >= IntegerCache.low && i <= IntegerCache.high时返回IntegerCache.cache[i + (-IntegerCache.low)]
当不符合时返回new Integer(i).
查看IntegerCache的源码,得到low为-128,high为127,即Integer的缓冲池大小为1个字节。则当Integer直接赋值时,值-128到127之间时,创建的对象存放在常量池中,直接从常量池中获取数据。因此i3==i4为true。
5. String 转基本数据类型
基本数据的包装类 Byte, Short, Integer, Long, Float, Double, Boolean 都有对应的方法可以将有数字字符组成的字符串转换为相应的基本数据类型.
注意: Character包装类没有对应的 parseCharacter() 方法. 还要注意字符串转为基本数据类型时对应类型的范围.
String a = "123";
String k = "true";
byte b = Byte.parseByte(a);
short i1 = Short.parseShort(a);
int i = Integer.parseInt(a);
long l = Long.parseLong(a);
float v = Float.parseFloat(a);
double v1 = Double.parseDouble(a);
boolean b1 = Boolean.parseBoolean(a);
System.out.println(b1); // false 为什么为false, 看源码
// public static boolean parseBoolean(String s) {
// return ((s != null) && s.equalsIoreCase("true"));
// }
// String 转为char[] 数组
char[] chars = a.toCharArray();
System.out.println(chars);
//String 转byte数组
byte[] bytes = a.getBytes();
System.out.println(bytes);
for (Byte bb : bytes){
System.out.println(bb);
}
6. 基本类型转String
String类相应的valueOf(byte b)、valueOf(long l)、valueOf(float f)、valueOf(double d)、valueOf(boolean b)可有参数的相应类型到字符串的转换.
我感觉基本类型转字符串类型直接加 “” 多快;
//char, byte数组转换为String,通过String构造器
char[] c = {'1', '2', '3'};
byte[] b = {49, 50, 51};
String s = new String(c);
String s1 = new String(b);
System.out.println(s);
System.out.println(s1);