Skip to content

数据类型

Java 是一门强类型语言,每个变量都必须声明其数据类型。Java 的数据类型分为两大类:基本数据类型和引用数据类型。

数据类型分类

text
┌─────────────────────────────────────────────────────────────────┐
│                       Java 数据类型                              │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  ┌──────────────────────┐    ┌──────────────────────────────┐  │
│  │    基本数据类型       │    │      引用数据类型             │  │
│  ├──────────────────────┤    ├──────────────────────────────┤  │
│  │  数值型:             │    │  类(class)                 │  │
│  │    整数:byte,short, │    │  接口(interface)            │  │
│  │          int,long    │    │  数组(array)                │  │
│  │    浮点:float,double│    │  枚举(enum)                 │  │
│  │  字符型:char        │    │  注解(annotation)           │  │
│  │  布尔型:boolean     │    │                              │  │
│  └──────────────────────┘    └──────────────────────────────┘  │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

基本数据类型

Java 共有 8 种基本数据类型,它们直接存储数据值,存储在栈内存中。

整数类型

类型占用空间取值范围默认值
byte1 字节-128 ~ 1270
short2 字节-32768 ~ 327670
int4 字节-2³¹ ~ 2³¹-10
long8 字节-2⁶³ ~ 2⁶³-10L
java
public class IntegerTypes {
    public static void main(String[] args) {
        // byte 类型:最小整数类型,节省内存
        byte byteVar = 127;
        System.out.println("byte: " + byteVar);
        
        // short 类型:短整型
        short shortVar = 32767;
        System.out.println("short: " + shortVar);
        
        // int 类型:最常用的整数类型
        int intVar = 2147483647;
        System.out.println("int: " + intVar);
        
        // long 类型:大整数,需要在数字后加 L 或 l
        long longVar = 9223372036854775807L;
        System.out.println("long: " + longVar);
        
        // 整数字面量表示法
        int decimal = 100;        // 十进制
        int binary = 0b1100100;   // 二进制(0b 前缀)
        int octal = 0144;         // 八进制(0 前缀)
        int hex = 0x64;           // 十六进制(0x 前缀)
        
        // Java 7+ 支持数字下划线分隔,提高可读性
        int million = 1_000_000;
        long creditCard = 1234_5678_9012_3456L;
        
        System.out.println("十进制: " + decimal);
        System.out.println("二进制: " + binary);
        System.out.println("八进制: " + octal);
        System.out.println("十六进制: " + hex);
        System.out.println("百万: " + million);
    }
}

浮点类型

类型占用空间取值范围默认值
float4 字节约 ±3.4E38(6-7位有效数字)0.0f
double8 字节约 ±1.8E308(15位有效数字)0.0d
java
public class FloatingTypes {
    public static void main(String[] args) {
        // float 类型:单精度浮点数,需要在数字后加 F 或 f
        float floatVar = 3.14159f;
        System.out.println("float: " + floatVar);
        
        // double 类型:双精度浮点数,默认的浮点类型
        double doubleVar = 3.141592653589793;
        System.out.println("double: " + doubleVar);
        
        // 科学计数法
        double scientific = 1.23e5;    // 1.23 × 10^5 = 123000.0
        double tiny = 1.23e-5;         // 1.23 × 10^-5 = 0.0000123
        
        System.out.println("科学计数法: " + scientific);
        System.out.println("小数: " + tiny);
        
        // 浮点数特殊值
        System.out.println("正无穷大: " + Double.POSITIVE_INFINITY);
        System.out.println("负无穷大: " + Double.NEGATIVE_INFINITY);
        System.out.println("非数字: " + Double.NaN);
        
        // 判断是否为 NaN
        double nanValue = 0.0 / 0.0;
        System.out.println("是否为 NaN: " + Double.isNaN(nanValue));
    }
}

字符类型

类型占用空间取值范围默认值
char2 字节0 ~ 65535(Unicode字符)'\u0000'
java
public class CharType {
    public static void main(String[] args) {
        // char 类型:单个 16 位 Unicode 字符
        char charA = 'A';           // 直接字符
        char charChinese = '中';     // 中文字符
        char charNum = '9';         // 数字字符
        char charSymbol = '@';      // 特殊符号
        
        // Unicode 编码表示
        char unicodeA = '\u0041';   // 'A' 的 Unicode 编码
        char unicodeChinese = '\u4e2d';  // '中' 的 Unicode 编码
        
        // 转义字符
        char newline = '\n';        // 换行
        char tab = '\t';            // 制表符
        char backslash = '\\';      // 反斜杠
        char singleQuote = '\'';    // 单引号
        char doubleQuote = '\"';    // 双引号
        
        System.out.println("字符 A: " + charA);
        System.out.println("中文字符: " + charChinese);
        System.out.println("Unicode A: " + unicodeA);
        System.out.println("Unicode 中: " + unicodeChinese);
        
        // 字符运算(基于 Unicode 编码)
        char nextChar = (char)(charA + 1);  // 'B'
        System.out.println("A 的下一个字符: " + nextChar);
    }
}

布尔类型

类型占用空间取值范围默认值
boolean1 位(实际实现可能不同)true / falsefalse
java
public class BooleanType {
    public static void main(String[] args) {
        // boolean 类型:只有 true 和 false 两个值
        boolean isJavaFun = true;
        boolean isHard = false;
        
        System.out.println("Java 有趣吗? " + isJavaFun);
        System.out.println("Java 难吗? " + isHard);
        
        // 比较运算结果
        int a = 10;
        int b = 20;
        boolean isGreater = a > b;    // false
        boolean isEqual = a == 10;    // true
        
        System.out.println("a > b: " + isGreater);
        System.out.println("a == 10: " + isEqual);
        
        // 逻辑运算
        boolean result = isJavaFun && !isHard;
        System.out.println("Java 有趣且不难: " + result);
    }
}

引用数据类型

引用类型存储的是对象的内存地址,对象存储在堆内存中。

字符串(String)

java
public class StringType {
    public static void main(String[] args) {
        // String 是引用类型,但使用广泛
        String greeting = "Hello, Java!";
        String name = new String("张三");  // 通过构造方法创建
        
        // 字符串连接
        String message = greeting + " 欢迎 " + name;
        System.out.println(message);
        
        // 常用方法
        System.out.println("长度: " + greeting.length());
        System.out.println("大写: " + greeting.toUpperCase());
        System.out.println("小写: " + greeting.toLowerCase());
        System.out.println("包含 Java: " + greeting.contains("Java"));
        System.out.println("索引位置: " + greeting.indexOf("Java"));
        System.out.println("子串: " + greeting.substring(0, 5));
        
        // 字符串比较
        String s1 = "hello";
        String s2 = "hello";
        String s3 = new String("hello");
        
        System.out.println("s1 == s2: " + (s1 == s2));         // true(字符串常量池)
        System.out.println("s1 == s3: " + (s1 == s3));         // false(不同对象)
        System.out.println("s1.equals(s3): " + s1.equals(s3)); // true(内容相同)
    }
}

数组

java
public class ArrayType {
    public static void main(String[] args) {
        // 数组声明和初始化
        int[] numbers = new int[5];          // 声明并分配空间
        String[] names = {"张三", "李四", "王五"};  // 声明并初始化
        
        // 赋值
        numbers[0] = 10;
        numbers[1] = 20;
        numbers[2] = 30;
        
        // 访问
        System.out.println("第一个数字: " + numbers[0]);
        System.out.println("数组长度: " + numbers.length);
        
        // 遍历数组
        for (int i = 0; i < names.length; i++) {
            System.out.println("姓名 " + i + ": " + names[i]);
        }
        
        // 增强 for 循环
        for (String name : names) {
            System.out.println("姓名: " + name);
        }
    }
}

自定义类

java
// 定义一个简单的类
class Student {
    String name;
    int age;
    
    public void study() {
        System.out.println(name + " 正在学习");
    }
}

public class ClassType {
    public static void main(String[] args) {
        // 创建对象
        Student student = new Student();
        student.name = "张三";
        student.age = 20;
        
        // 调用方法
        student.study();
        System.out.println("学生姓名: " + student.name);
        System.out.println("学生年龄: " + student.age);
    }
}

类型转换

自动类型转换(隐式转换)

从小类型到大类型自动转换,不会丢失精度。

text
byte → short → int → long → float → double
          ↘         ↗
            char → int
java
public class AutoConversion {
    public static void main(String[] args) {
        // 自动类型转换
        byte byteVar = 10;
        short shortVar = byteVar;    // byte → short
        int intVar = shortVar;       // short → int
        long longVar = intVar;       // int → long
        float floatVar = longVar;    // long → float
        double doubleVar = floatVar; // float → double
        
        System.out.println("byte: " + byteVar);
        System.out.println("short: " + shortVar);
        System.out.println("int: " + intVar);
        System.out.println("long: " + longVar);
        System.out.println("float: " + floatVar);
        System.out.println("double: " + doubleVar);
        
        // char 到 int 的转换
        char charVar = 'A';
        int charToInt = charVar;     // char → int(ASCII 值)
        System.out.println("字符 A 的 ASCII 值: " + charToInt);  // 65
        
        // 表达式中的自动类型提升
        int a = 10;
        double b = 3.14;
        double result = a + b;       // int 自动提升为 double
        System.out.println("结果: " + result);
    }
}

强制类型转换(显式转换)

从大类型到小类型需要强制转换,可能会丢失精度。

java
public class ForceConversion {
    public static void main(String[] args) {
        // 强制类型转换语法:(目标类型)值
        double doubleVar = 3.14159;
        int intVar = (int) doubleVar;  // 强制转换,丢失小数部分
        System.out.println("double 转 int: " + intVar);  // 3
        
        // 大整数转小整数
        long longVar = 1000L;
        byte byteVar = (byte) longVar;
        System.out.println("long 转 byte: " + byteVar);  // 正常
        
        // 溢出情况
        int bigInt = 130;
        byte overflow = (byte) bigInt;
        System.out.println("int 130 转 byte: " + overflow);  // -126(溢出)
        
        // 浮点数转整数
        float floatVar = 99.9f;
        int truncated = (int) floatVar;
        System.out.println("float 转 int: " + truncated);  // 99(截断)
        
        // 四舍五入
        long rounded = Math.round(floatVar);
        System.out.println("四舍五入: " + rounded);  // 100
    }
}

字符串与其他类型的转换

java
public class StringConversion {
    public static void main(String[] args) {
        // 其他类型转字符串
        int num = 100;
        String str1 = String.valueOf(num);      // 使用 valueOf
        String str2 = Integer.toString(num);    // 使用 toString
        String str3 = num + "";                 // 字符串连接
        
        System.out.println("int 转 String: " + str1);
        
        double d = 3.14;
        String str4 = String.valueOf(d);
        System.out.println("double 转 String: " + str4);
        
        boolean bool = true;
        String str5 = String.valueOf(bool);
        System.out.println("boolean 转 String: " + str5);
        
        // 字符串转其他类型
        String numStr = "12345";
        int parsedInt = Integer.parseInt(numStr);
        System.out.println("String 转 int: " + parsedInt);
        
        String doubleStr = "3.14159";
        double parsedDouble = Double.parseDouble(doubleStr);
        System.out.println("String 转 double: " + parsedDouble);
        
        String boolStr = "true";
        boolean parsedBool = Boolean.parseBoolean(boolStr);
        System.out.println("String 转 boolean: " + parsedBool);
        
        // 注意:转换失败会抛出 NumberFormatException
        try {
            String invalid = "abc";
            int invalidNum = Integer.parseInt(invalid);  // 抛出异常
        } catch (NumberFormatException e) {
            System.out.println("转换失败: " + e.getMessage());
        }
    }
}

类型判断

java
public class TypeCheck {
    public static void main(String[] args) {
        // instanceof 运算符:判断对象是否为某个类的实例
        String str = "Hello";
        System.out.println("str 是 String 的实例: " + (str instanceof String));  // true
        System.out.println("str 是 Object 的实例: " + (str instanceof Object));  // true
        
        // 获取对象的类信息
        Object obj = "Hello";
        System.out.println("obj 的类名: " + obj.getClass().getName());
        System.out.println("obj 是 String 类型: " + (obj.getClass() == String.class));
        
        // 包装类的类型判断
        Integer num = 100;
        System.out.println("num 是 Integer 的实例: " + (num instanceof Integer));
        System.out.println("num 是 Number 的实例: " + (num instanceof Number));
    }
}

包装类

每个基本数据类型都有对应的包装类,用于在需要对象的场景中使用。

基本类型包装类
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean
java
public class WrapperClass {
    public static void main(String[] args) {
        // 装箱:基本类型 → 包装类
        int primitive = 100;
        Integer boxed = Integer.valueOf(primitive);  // 显式装箱
        Integer autoBoxed = primitive;               // 自动装箱
        
        // 拆箱:包装类 → 基本类型
        int unboxed = autoBoxed.intValue();          // 显式拆箱
        int autoUnboxed = autoBoxed;                 // 自动拆箱
        
        System.out.println("装箱: " + boxed);
        System.out.println("拆箱: " + unboxed);
        
        // 包装类的常用方法
        System.out.println("最大值: " + Integer.MAX_VALUE);
        System.out.println("最小值: " + Integer.MIN_VALUE);
        System.out.println("字节大小: " + Integer.BYTES);
        System.out.println("二进制字符串: " + Integer.toBinaryString(10));
        System.out.println("十六进制字符串: " + Integer.toHexString(255));
        
        // 注意:包装类比较要用 equals
        Integer a = 128;
        Integer b = 128;
        System.out.println("a == b: " + (a == b));         // false(-128~127 缓存范围外)
        System.out.println("a.equals(b): " + a.equals(b)); // true
    }
}

小结

本章我们学习了:

  • 基本数据类型:byte、short、int、long、float、double、char、boolean
  • 引用数据类型:类、接口、数组、枚举
  • 类型转换:自动类型转换和强制类型转换
  • 字符串转换:与其他类型的相互转换
  • 包装类:基本类型的对象包装

下一章,我们将学习 运算符,了解 Java 中的各种运算操作。