数据类型拓展
整数型
- 进制:二进制:0b 八进制:0 十进制 十六进制:0x 例:
public class Demo{
public static void main(String[] args){
int num1 = 0b10;
int num2 = 10;
int num3 = 010;
int num4 = 0x10;
System.out.println(num1); // 2
System.out.println(num2); // 10
System.out.println(num3); // 8
System.out.println(num4); // 16
}
}
浮点型
-
数据计算与比较大小最好完全避免使用浮点数。浮点数有:有限、离散、有舍入误差、接近但不等于等特点。
-
如需数据计算例如银行业务则需要使用BigDecimal类。
public class Demo{
public static void main(String[] args){
float f1 = 0.1f;
double d1 = 1.0/10;
System.out.println(f1 == d1); //false
float f2 = 3.1415926;
float f3 = f2 + 1;
System.out.println(f2 == f3); //true
}
}
字符型
- 字符的本质是数字,使用Unicode编码,占2字节,最多表示65536个字符。U0000~UFFFF
public class Demo{
public static void main(String[] args){
char c1 ='a';
char c2 = '中';
System.out.println(c1); // a
System.out.println((int)c1); // 97
System.out.println(c2); // 中
System.out.println((int)c2); //20013
//(int):强制转换为整数型
char c3 ='\u0061';
/* \u:转义字符编码转换
类似的还有:\n 换行;\t水平制表符(tab)...
*/
System.out.println(c3); /a
}
}
布尔型
public class Demo{
public static void main(String[] args){
boolean flag = true;
if(flag==true);{
//if(flag){}:Less is more,代码要精简易读。
System.out.println("Do the best");
}
}
}
字符串类
public class Demo{
public static void main(String[] args){
String sa = new String("hello world");
String sb = new String("hello world");
System.out.println(sa==sb); //false
//new 创建了新的两个不同的对象,==比较对象地址,所以不相等
}
}