-
数据类型作用:数据类型不同,空间大小不同。
-
数据类型分类:基本数据类型、引用数据类型
- 基本数据类型:整数型、浮点型、布尔型、字符型
- 八小种:byte,short,int ,long,
- float,double,
- boolean,
- char
- 引用类型:String属于引用类型。
整数型:byte、short、int、long区别:占用空间大小。
char 占2个字节
boolean 1
float 4
double 8
byte 1
short 2
int 4
long 8

byte:[-128 ~ 127]
short:[-32768 ~ 32767]
int:[-2147483648 ~ 2147483647]
char:[0 ~ 65535]
-
short和char实际容量相同,不过char可以表示更大的数字,因为char表示的是文字,文字没有正负之分,所以char可以标识更大的数字。
-
其中byte,short,int,long,float,double,boolean这7中计算机表示起来比较容易,都是数字。
-
对于char类型来说计算机表示起来比较麻烦,各个国家的文字不一样,文字不能直接通过自然算法转换成二进制,因此字符编码诞生了。
-
什么事字符编码:字符编码是人为的定义的一套转换表,在字符编码中规定了一系列的文字对应的二进制。字符编码其实本质就是一本字典,该字段中描述了文字与二进制之间的对应关系。字符编码是人为规定的。
-
ASCII编码采用1byte进行存储。
-
ISO-8859-1编码方式向上兼容ASCII码 不支持中文。
-
中文编码:GB2312<GBK<GB18030 容量关系
-
繁体中文:big5
-
Java采用Unicode编码。(utf8,utf16,utf32)
public class CharTest{
public static void main(String[] args){
//char可以存储1个汉字,占用2个字节。
char c1 = '中';
char c2 = 'a';
char c3 = '0';
char c4 = 't';
//转义字符
char c5 = '\t'; //\t制表符
\负责转义
System.out.print("hello"); //不换行
System.out.println("hello"); //换行
'\n' 换行
\u表示后面的是一个字符的Unicode编码,Unicode编码是十六进制的。
}
}
//IntTest
public class IntTest{
public static void main(String[] args){
//任何情况下,整数型的字面量/数据默认当做int类型处理。
//如果希望被当作long类型,需要在字面量上加L/l
int a = 100;
long b = 100L;
//自动类型转换,int类型->long类型。
long c = 100;
//自动类型转换
long d = 2147483647;
//默认字面量当作int类型,数字2147483648超出int范围,在没有赋值之前就出错。
long e = 2147483648;
//小容量可以赋值给大容量,称为自动类型转换
long x = 100L;
//int y = x; //编译出错,大容量转换小容量必须强制类型转换。
int y = (int)x; //编译虽然过了,运行时可能损失精度。
//long类型100L强制转换int类型,自动把前4字节砍掉。
//在没有超出byte范围时,可以赋值byte类型。
}
}
public class CharTest{
public static void main(String[] args){
char c1 = 'a';
char c2 = 97; //会类型转换吗?整数可以直接赋值char,并且输出英文
//int整数赋值给char类型变量会自动转换成char类型,最终一个字符。
//当一个整数没有超出byte,short,char的取值范围时,可以直接赋值给byte,short,char。
}
}
public class IntTest{
public static void main(String[] args){
//计算机在任何情况下只能识别二进制
//计算机在底层存储数据的时候,一律存储的是二进制补码形象。
byte b = (byte)150;
System.out.println(b);//结果为多少?
//byte,char,short做混合运算,各自先转换成int再做运算。
char c1 = 'b';
byte b1 = 1;
short s = c1+b1; //出错。
short s = (short)(c1+b1);
}
}
public class IntTest{
public static void main(String[] args){
long a = 10L;
char c = 'a';
short s = 100;
int i = 30;
System.out.println(a+c+s+i);
int x = (int)(a+c+s+i);
System.out.println(x);
//多种数据类型做混合运算,最终的结果类型是最大容量的对应类型。
int tmp = 10 / 3;
int tmp2 = 1 / 2;
}
}
public class FloatTest{
public static void main(String[] args){
//float单精度
//double双精度
//java.math.BigDecimal(不是基本数据类型,属于引用数据类型)用于银行财务。
//long类型占用8个字节,float类型占用4字节。
//任意一个浮点型都比整数型空间大。因此,float容量大。
//任何一个浮点型字面量默认为double类型,如果当作float类型,字面量后加F/f
double pi = 3.1415926; //不存在类型转换。
float f = 3.14; //出错
float f = 3.14f;
int i = 10.0/5; //出错,=后为double类型。
}
}
public class BoolleanTest{
public static void main(String[] args){
//Java中boolean只有两个值true,false,与C不同,C可以用1和0 表示。
//使用在逻辑判断,通常放在条件中。
boolean xingBie = 1; //出错,int无法转换boolean类型。
boolean xingBie = true;
}
}
-
byte <short(char) < int < long < float << double 其中char和short都占2字节,但char可以标识更大的正整数。
-
boolean不能参与类型转换,其他都行
网友评论