数据类型
基本类型
数值类型
整数类型 | ||
---|---|---|
类型 | 内存(/字节) | 范围 |
byte | 1 | -128~127 |
short | 2 | -32768~32767 |
int | 4 | -2147483648~2147483647 |
long | 8 | -9223372036854775808~9223372036854775807 |
public class 数据类型 {
public static void main(String[] args) {
//整数
int a=10;//常用
byte b=10;
short c=10;
long d=10L;//long类型加L
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
}
浮点类型(小数) | |
---|---|
类型 | 内存(/字节) |
float | 4 |
double | 8 |
public class 数据类型 {
public static void main(String[] args) {
// 浮点数
float a=1.1F;//float类型加F
double b=1.1;
System.out.println(a);
System.out.println(b);
}
}
注意:浮点数舍入误差大,不能用于比较
字符类型
char 占2字节
public class 数据类型 {
public static void main(String[] args) {
//String ="hallo";
char a='b';
System.out.println(a);
}
}
可通过Unicode表转为数字
boolean类型(是非)
占1位,其值只有true和false两个
public class 数据类型 {
public static void main(String[] args) {
//boolean类型
boolean flag=true;
System.out.println(flag);
}
}
引用类型
类
接口
数组
字符类型转换
部分运算时由于数据类型不同,需进行字符类型转换
优先级:浮点>整数,容量大>容量小
(byte,short,char)<int<long<float<double
强制转换
优先级:高→低
格式:(目的类型)+变量名称
int i=10; byte b=(byte)i;
自动转换
优先级:低→高
注意:不能对boolean值转换,注意内存溢出和精度问题
转义字符
\t 制表符
\n 换行