12.数据类型
-
强类型语言(Java , C , C++)
- 要求变量的使用必须要严格符合规定,所有的变量要先声明才能使用
-
弱类型语言( JavaScript)
-
Java的数据类型
- 基本数据类型
- 引用数据类型
一个字节8bit , 8位2进制数
- 整数类型
- byte 占用1个字节,范围: -128~127
- short 占用2个字节,范围: -32768~32767
- int 占用4个字节,范围:-2147483648~2147483647
- long 占用8个字节,范围:-9223372036854775808~9223372036854775807 必须要以L或l结尾
- 浮点数类型
- float占用4个字节 必须以F或f结尾
- double占用8个字节
- 字符类型
- char占用2个字节
- 布尔类型
- boolean 只占用1位
public class Demo2 {
public static void main(String[] args) {
/*
* 整数类型
* */
byte num1 = 127;
// byte num$1 = 128; // 报错
short num2 = 32767;
// short num$2 = 32768; // 报错
int num3 = 2147483647;
// int num$3 = 2147483648; // 报错
long maxNum = 9223372036854775807L; // 必须要以L或l结尾
/*
* 浮点数类型
* */
float floatNum = 1.35F; // 必须以 F或f 结尾
double doubleNum = 1.35;
/*
字符类型
* */
char char1 = '字';
char char2 = '2' ;
// char char3 = "字"; //报错
// char char4 = '字符'; // 报错
String string = "这是一个字符串"; // 注意String不是关键字,它是一个类
/*
* 布尔类型 只有 true 和 false 两个值,是与非
* */
boolean bool1 = true;
boolean bool2 = false;
// boolean bool$1 = 0; // 报错
// boolean bool$2 = 1; // 报错
}
}
- 小科普,32位电脑和64位电脑有什么区别?
- 32位计算机最多可以搭载4GB的内存
- 64位计算机最多可以搭载128GB的内存
整数扩展
- 二进制 以0b开头
- 八进制 以0开头
- 十进制
- 十六进制 以0x开头 0~9 A~F
public class Demo3 {
public static void main(String[] args) {
// 进制问题 二进制0b 八进制0 十进制 十六进制0x
int num1 = 10;
int num2 = 0b10;
int num3 = 010;
int num4 = 0x11;
System.out.println(num1);
System.out.println(num2);
System.out.println(num3);
System.out.println(num4);
}
}
输出结果:
浮点数扩展
- 银行业务怎么表示? 钱?
public class Demo4 {
public static void main(String[] args) {
/*
* 浮点数安全问题 银行业务表示?
* BigDecimal 类 数学工具类,用来解决这一问题
* */
/*
* float 有限 离散 舍入误差 大约 接近但不相等!!
* 最好不要直接拿浮点数进行比较
* */
float floatNum1 = 0.1f;
float floatNum2 = 1 / 10;
System.out.println(floatNum1 == floatNum2); // false ?
float floatNum3 = 46843587841f;
float floatNum4 = floatNum3 + 1;
System.out.println(floatNum3 == floatNum4); // true ?
}
}
输出结果:
字符扩展
布尔扩展
public class Demo5 {
public static void main(String[] args) {
/*
字符扩展
* */
char char1 = 'a';
char char2 = '中';
System.out.println(char1);
System.out.println((int) char1); // int 强制类型转换
System.out.println(char2);
System.out.println((int) char2);
// Unicode编码 2个字节 a --> 97 , 中 --> 20013
int intNum1 = 20013;
char char3 = '\u0061';
System.out.println(char3); // a
System.out.println((char) intNum1); // char 强制类型转换 --> 中
// 转译字符 \n 换行 \t 制表符 \r 回退
System.out.println("hello\tworld");
System.out.println("hello\nworld");
System.out.println("hello\rworld");
String str1 = "helloworld";
String str2 = "helloworld";
System.out.println(str1 == str2); // true
String str3 = new String("hello");
String str4 = new String("hello");
System.out.println(str3 == str4); // false
// 布尔值扩展
// Boolean flag = true;
// if (flag == true){ //新手
//
// }
// 这两种写法是一样的意思
// if (flag){} // 老手
}
}
运行结果: