【Java 基础】变量、基本数据类型与数组——核心要点与代码实战

前言

本文整理 Java 变量体系、8 种基本数据类型和数组操作的核心知识点,附完整可运行代码。适合入门学习和面试复习。


一、变量分类

Java 变量按声明位置分为四种:

public class VariableTypes {
    // ① 类变量(静态字段)—— 全类共享一份
    static int classVar = 0;

    // ② 实例变量(非静态字段)—— 每个对象独立一份
    int instanceVar = 0;

    // ④ 参数 —— 调用者传入
    public void method(int param) {
        // ③ 局部变量 —— 方法内部,无默认值
        int localVar = 10;
        System.out.println(localVar + param);
    }
}

关键区别

实例变量 类变量 局部变量 参数
位置 类体内 类体内+static 方法内 方法签名
默认值 调用者传
生命周期 对象 方法 方法

二、8 种基本数据类型

2.1 完整定义

public class PrimitiveTypes {
    public static void main(String[] args) {
        // 整数类型
        byte   b = 127;                    // 1字节, -128~127
        short  s = 32767;                  // 2字节, -32768~32767
        int    i = 2_147_483_647;          // 4字节, 约±21亿
        long   l = 9_223_372_036_854_775_807L; // 8字节, 加L

        // 浮点类型
        float  f = 3.14f;                  // 4字节, 加f
        double d = 3.141592653589793;      // 8字节, 默认

        // 其他类型
        boolean bool = true;               // true/false
        char    c = 'A';                   // 2字节, 0~65535

        System.out.println("byte:    " + b);
        System.out.println("short:   " + s);
        System.out.println("int:     " + i);
        System.out.println("long:    " + l);
        System.out.println("float:   " + f);
        System.out.println("double:  " + d);
        System.out.println("boolean: " + bool);
        System.out.println("char:    " + c + " (Unicode: " + (int)c + ")");
    }
}

2.2 默认值表

类型 默认值 类型 默认值
byte 0 float 0.0f
short 0 double 0.0d
int 0 boolean false
long 0L char '\u0000'

注意:仅限字段(成员变量)。局部变量没有默认值,必须初始化。


三、字面量与进制

3.1 整数字面量

int dec = 26;        // 十进制
int hex = 0x1A;      // 十六进制 (0x前缀)
int bin = 0b11010;   // 二进制   (0b前缀)
// 三者值相同

3.2 下划线分组

long phone = 138_1234_5678L;   // 提升可读性
int million = 1_000_000;
byte mask = 0b0010_0101;

规则:下划线只能放在数字之间,不能在开头/结尾/小数点旁/后缀前。

3.3 后缀规则

  • long 字面量 → 加 L(推荐大写)
  • float 字面量 → 加 f
  • double 字面量 → 可选加 d(默认就是 double,通常省略)

四、类型转换

4.1 自动拓宽(安全)

byte → short → int → long → float → double
              char ↗

4.2 强制窄化(危险)

double pi = 3.99;
int n = (int) pi;        // 3(截断,不是四舍五入)

int big = 130;
byte b = (byte) big;     // -126(溢出)

4.3 运算提升

byte a = 50, b = 60;
// byte c = a + b;       // ❌ 编译错误
int c = a + b;            // ✅ byte运算自动提升为int

五、浮点精度问题

import java.math.BigDecimal;

public class PrecisionDemo {
    public static void main(String[] args) {
        // 问题演示
        System.out.println(0.1 + 0.2);          // 0.30000000000000004
        System.out.println(0.1 + 0.2 == 0.3);   // false

        // 正确做法:BigDecimal + String构造
        BigDecimal a = new BigDecimal("0.1");
        BigDecimal b = new BigDecimal("0.2");
        System.out.println(a.add(b));             // 0.3
        System.out.println(a.add(b).equals(new BigDecimal("0.3"))); // true
    }
}

六、整数溢出

public class OverflowDemo {
    public static void main(String[] args) {
        int max = Integer.MAX_VALUE;
        System.out.println(max);       // 2147483647
        System.out.println(max + 1);   // -2147483648(静默溢出!)

        // 安全运算
        try {
            Math.addExact(max, 1);
        } catch (ArithmeticException e) {
            System.out.println("检测到溢出: " + e.getMessage());
        }
    }
}

七、数组

7.1 基本操作

import java.util.Arrays;

public class ArrayBasic {
    public static void main(String[] args) {
        // 创建
        int[] arr1 = new int[5];
        int[] arr2 = {10, 20, 30, 40, 50};

        // 访问
        System.out.println(arr2[0]);       // 10
        System.out.println(arr2.length);   // 5

        // 遍历
        for (int val : arr2) {
            System.out.print(val + " ");
        }
        System.out.println();

        // 打印
        System.out.println(Arrays.toString(arr2)); // [10, 20, 30, 40, 50]
    }
}

7.2 Arrays 工具类

import java.util.Arrays;

public class ArrayToolkit {
    public static void main(String[] args) {
        int[] data = {5, 3, 8, 1, 9, 2};

        // 排序
        int[] sorted = Arrays.copyOf(data, data.length);
        Arrays.sort(sorted);
        System.out.println("排序: " + Arrays.toString(sorted));

        // 搜索(需已排序)
        int idx = Arrays.binarySearch(sorted, 8);
        System.out.println("8的索引: " + idx);

        // 比较
        System.out.println("相等? " + Arrays.equals(data, sorted));

        // 填充
        int[] filled = new int[5];
        Arrays.fill(filled, -1);
        System.out.println("填充: " + Arrays.toString(filled));

        // 复制范围
        int[] sub = Arrays.copyOfRange(data, 1, 4);
        System.out.println("子数组: " + Arrays.toString(sub));
    }
}

7.3 多维数组

public class MultiArray {
    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6}
        };

        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.printf("%3d", matrix[i][j]);
            }
            System.out.println();
        }
    }
}

八、命名规范

种类 规则 示例
普通变量 小驼峰 userName, maxSpeed
常量 全大写+下划线 MAX_SIZE, PI
方法 小驼峰 getUserName()
大驼峰 ArrayDemo, StudentInfo

变量名不能是关键字(int, class, public 等),区分大小写,以字母开头(不推荐 $_ 开头)。


九、面试要点

  1. 8 种基本类型:byte, short, int, long, float, double, boolean, char。String 不是。
  2. 默认值:字段有,局部变量没有。
  3. 浮点精度:0.1+0.2≠0.3,金额用 BigDecimal(String 构造)。
  4. 溢出:int 溢出是静默的,用 Math.xxxExact 检测。
  5. 类型提升:byte+byte=int。
  6. 数组长度固定,创建后不能改变。ArrayList 底层用数组+扩容实现。

作者:IT探险家 | 本文同步发布于个人博客和公众号

posted @ 2026-02-27 16:21  IT探险家  阅读(1)  评论(0)    收藏  举报