Java数据类型
数据类型
变量名 = 变量值
基本类型
位(bit)
是计算机内部数据存储
的最小单位,11001100
是一个八位
二进制数
字节(byte)
是计算机中数据处理
的基本单位,习惯上使用B
进行表示
1B(byte,字节) = 8bit(位)
字符:是指计算机中使用的字母、数字、字和、符号。
整数类型
byte
占一个字节范围short
占两个字节范围int
占四个字节范围long
占八个字节范围
浮点类型
float
占四个字节double
占八个字节
字符类型
char
占两个字节
boolean类型
boolean
占一位其值只有true或者false
总结代码演示
public class HelloWorld {
public static void main(String[] args) {
//八大基本数据类型
//整数
byte num1 = 10;
short num2 = 20;
int num3 = 30;
long num4 = 40L;
//小数:浮点类型
float num5 = 5.6F;
double num6 = 5.7;
//字符类型
char char1 = 'a';
//字符串String不是关键字,是一个类
String name = "akita";
//boolean类型
boolean logic = true;
}
}
引用类型
类
接口
数组
数据类型拓展
整数拓展
public class HelloWorld {
public static void main(String[] args) {
int i1 = 10; //十进制
int i2 = 010; //八进制
int i3 = 0x10; //十六进制
System.out.println(i1);
System.out.println(i2);
System.out.println(i3);
}
}
/*
输出如下
10
8
16
*/
浮点数拓展
float数据类型的问题:有限,离散,舍入误差、大约、接近但是不等于
避免使用浮点数进行比较
避免使用浮点数进行比较
避免使用浮点数进行比较
问题演示:
public class HelloWorld {
public static void main(String[] args) {
float f = 0.1f; //0.1
double d = 1.0 / 10; //0.1
System.out.println(f == d);
System.out.println(f);
System.out.println(d);
float a = 212121212212121121f;
float b = a + 1;
System.out.println(a == b);
}
}
输出结果:
字符类型拓展
字符类型强制转换
public class HelloWorld {
public static void main(String[] args) {
char c1 = 'a';
char c2 = '中';
System.out.println(c1);
System.out.println((int) c1);
System.out.println(c2);
System.out.println((int) c2);
}
}
输出如下:
a
97
中
20013
转义字符
\t
:制表符\n
:换行符
==的区别
public class HelloWorld {
public static void main(String[] args) {
String sa = "akita";
String sb = "akita";
System.out.println(sa == sb);
String sc = new String("hello");
String sd = new String("hello");
System.out.println(sc == sd);
}
}
代码输出:
true
false
boolean类型拓展
public class HelloWorld {
public static void main(String[] args) {
boolean flag = true;
if (flag == true) {
}
//与上述逻辑相同
// if(flag){
//
// }
}
}
类型转换
低------------------------------------------------->高
byte,short,char–>int–>long–>float–>double
运算中,不同类型的数据先转化为同一类型,然后进行运算。
强制类型转换
优先级从高到低需要进行强制类型转换
public class HelloWorld {
public static void main(String[] args) {
int i = 128;
byte b = (byte) i;
System.out.println(i);
System.out.println(b);
}
}
自动类型转换
优先级从低到高会进行自动类型转换
public class HelloWorld {
public static void main(String[] args) {
int i = 128;
double b = i;
System.out.println(i);
System.out.println(b);
}
}
注意点
- 不能对布尔值进行转换
- 不能把对象类型转换为不相干的类型
- 在把高容量转换到低容量的时候,强制转换
- 转换的时候可能存在内存溢出,或者精度问题