18.基础语法-数据类型
18 数据类型
18.1 基本数据类型
包含8种简单类型数据,比如:数字、字符等
| 数据类型 | 内存占用(Byte) | 数据范围 | |
| 整型 | byte | 1 | -128 ~ 127 |
| short | 2 | -32768 ~ 32767 | |
| int | 4 | -2147483648 ~ 2147483647 | |
| long | 8 | -9223372036854775807~9223372036854775807 | |
| 浮点型(小数) | float | 4 | 1.401298 E -45 到 3.4028235 E +38 |
| double | 8 | 4.9000000 E-324 到 1.797693 E +308 | |
| 字符型 | char | 2 | unicode码点范围(0 ~ 65535) |
| 布尔型 | boolean | 1 | true、false |
18.2 演示
鼠标放到 com.itheima 行,新建 New -> Java Class -> 输入 chap04.DataTypesDemo(直接创建包及包下的类)
package com.itheima.chap04; public class DataTypesDemo { public static void main(String[] args) { // 输入 main 回车, 自动生成 main 方法 // 1.整数类型 byte short int long 整数字面量默认是 int 类型 byte b = 127; // byte 取值范围 127 ~ -128 // byte b = -129; 错误: java: 值 -129 不在类型 byte 的范围内 short s = 32767; // short 取值范围 32767 ~ -32768 // short s = 32768; 错误: java: 值 32768 不在类型 short 的范围内 int i = 2147483647; // int 取值范围 2147483647 ~ -2147483648 // int i = 2147483648; // 错误: java: 值 2147483648 不在类型 int 的范围内 long l = 9223372036854775807L; // long 取值范围 9223372036854775807 ~ -9223372036854775808 整数字面量默认是 int 类型, long 类型超出 int 取值范围,需要加上 L, 表示 long 类型 // long l = 9223372036854775808L; 错误: java: 值 9223372036854775808L 不在类型 long 的范围内 // 2.浮点数 float double 浮点数字面量默认是 double 类型 float f = 3.14F; // float 取值范围 3.14 ~ -3.14 // float f = 3.15; 错误: java: 值 3.15 不在类型 float 的范围内 浮点数字面量默认是 double 类型, double 类型超出 float 取值范围,需要加上 F,表示 float 类型 double d = 3.14; // 3.字符 char 字符需要单引号引起来 char c = 'a'; // 字符是单个字符 // char c = 'abc'; 错误: java: 值 abc 不在类型 char 的范围内 char c1 = '中'; // 输出 中 System.out.println(c1); char c2 = 97; // 输出 a ,给 char类型赋值整数,整数会被当做码点,存储的其实是对应的字符 System.out.println(c2); // 4.布尔型 boolean, 表示真或假 布尔型只有两个值 true false boolean b1 = true; boolean b2 = false; // 5.字符串 属于引用数据类型, 类型名叫 String String str = "hello world"; System.out.println(str); } } ------------------------------------------------ 执行后 D:\Software\jdk17\bin\java.exe "-javaagent:D:\Software\JetBrainsIntelliJ IDEA 2025.2.4\lib\idea_rt.jar=3409" -Dfile.encoding=UTF-8 -classpath D:\Software\JavaCode\p1-basic\out\production\p1-basic com.itheima.chap04.DataTypesDemo 中 a hello world Process finished with exit code 0
18.3 引用数据类型
Java中除8种基本类型以外的所有其他数据类型
后面在面向对象中详细讲解
———————————————————————————————————————————————————————————————————————————
无敌小马爱学习
浙公网安备 33010602011771号