当前位置: 首页 > news >正文

Java基础全面复盘:从入门到进阶的核心要点梳理

引言

Java作为一门经典的面向对象编程语言,自1995年诞生以来,始终保持着旺盛的生命力。无论你是刚刚接触Java的初学者,还是希望巩固基础的开发者,进行一次全面的基础复盘都大有裨益。本文将系统性地梳理Java核心知识点,帮助你构建完整的知识体系。

一、Java开发环境搭建

JDK安装与配置

# 检查Java版本
java -version
javac -version# 设置环境变量(示例)
JAVA_HOME=/path/to/jdk
PATH=$JAVA_HOME/bin:$PATH

二、Java基础语法

变量与数据类型

public class DataTypes {public static void main(String[] args) {// 基本数据类型byte b = 127;           // 8位short s = 32767;        // 16位int i = 2147483647;     // 32位long l = 9223372036854775807L;  // 64位float f = 3.14f;        // 32位浮点double d = 3.1415926535; // 64位浮点char c = 'A';           // 16位Unicodeboolean bool = true;    // 1位// 引用数据类型String str = "Hello Java";int[] array = {1, 2, 3};}
}

运算符详解

public class Operators {public static void main(String[] args) {int a = 10, b = 3;// 算术运算符System.out.println(a + b);  // 13System.out.println(a - b);  // 7System.out.println(a * b);  // 30System.out.println(a / b);  // 3System.out.println(a % b);  // 1// 关系运算符System.out.println(a > b);   // trueSystem.out.println(a == b);  // false// 逻辑运算符boolean x = true, y = false;System.out.println(x && y);  // falseSystem.out.println(x || y);  // trueSystem.out.println(!x);      // false// 三元运算符int max = (a > b) ? a : b;  // 10
    }
}

流程控制结构

public class ControlFlow {public static void main(String[] args) {// if-else语句int score = 85;if (score >= 90) {System.out.println("优秀");} else if (score >= 80) {System.out.println("良好");  // 输出这个} else {System.out.println("及格");}// switch语句int day = 3;switch (day) {case 1:System.out.println("星期一");break;case 2:System.out.println("星期二");break;case 3:System.out.println("星期三");  // 输出这个break;default:System.out.println("其他");}// 循环结构for (int i = 0; i < 5; i++) {System.out.println("for循环: " + i);}int j = 0;while (j < 3) {System.out.println("while循环: " + j);j++;}int k = 0;do {System.out.println("do-while循环: " + k);k++;} while (k < 3);}
}

三、面向对象编程

类与对象

// 类的定义
public class Person {// 字段(属性)private String name;private int age;// 构造方法public Person() {this.name = "未知";this.age = 0;}public Person(String name, int age) {this.name = name;this.age = age;}// 方法public void introduce() {System.out.println("我叫" + name + ",今年" + age + "岁");}// Getter和Setterpublic String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {if (age >= 0) {this.age = age;}}
}// 使用类
public class OOPDemo {public static void main(String[] args) {Person person1 = new Person();Person person2 = new Person("张三", 25);person1.introduce();  // 我叫未知,今年0岁person2.introduce();  // 我叫张三,今年25岁
    }
}

三大特性:封装、继承、多态

// 封装示例
public class BankAccount {private double balance;public void deposit(double amount) {if (amount > 0) {balance += amount;}}public boolean withdraw(double amount) {if (amount > 0 && balance >= amount) {balance -= amount;return true;}return false;}public double getBalance() {return balance;}
}// 继承示例
class Animal {protected String name;public Animal(String name) {this.name = name;}public void eat() {System.out.println(name + "在吃东西");}
}class Dog extends Animal {public Dog(String name) {super(name);}public void bark() {System.out.println(name + "在汪汪叫");}// 方法重写
    @Overridepublic void eat() {System.out.println(name + "在吃狗粮");}
}// 多态示例
public class PolymorphismDemo {public static void main(String[] args) {Animal myAnimal = new Dog("旺财");myAnimal.eat();  // 旺财在吃狗粮 - 多态的表现
    }
}

抽象类与接口

// 抽象类
abstract class Shape {protected String color;public Shape(String color) {this.color = color;}// 抽象方法public abstract double calculateArea();// 具体方法public void displayColor() {System.out.println("颜色: " + color);}
}class Circle extends Shape {private double radius;public Circle(String color, double radius) {super(color);this.radius = radius;}@Overridepublic double calculateArea() {return Math.PI * radius * radius;}
}// 接口
interface Flyable {void fly();  // 隐式抽象方法default void takeOff() {  // 默认方法System.out.println("准备起飞");}static void showFeature() {  // 静态方法System.out.println("可以飞行");}
}interface Swimmable {void swim();
}// 实现多个接口
class Duck implements Flyable, Swimmable {@Overridepublic void fly() {System.out.println("鸭子在飞行");}@Overridepublic void swim() {System.out.println("鸭子在游泳");}
}

四、异常处理

异常体系结构

public class ExceptionHandling {public static void main(String[] args) {// try-catch-finallytry {int result = divide(10, 0);System.out.println("结果: " + result);} catch (ArithmeticException e) {System.out.println("捕获算术异常: " + e.getMessage());} catch (Exception e) {System.out.println("捕获其他异常: " + e.getMessage());} finally {System.out.println("finally块总是执行");}// 抛出异常try {checkAge(15);} catch (IllegalArgumentException e) {System.out.println(e.getMessage());}}public static int divide(int a, int b) {return a / b;}public static void checkAge(int age) {if (age < 18) {throw new IllegalArgumentException("年龄必须大于等于18岁");}System.out.println("年龄验证通过");}
}// 自定义异常
class InsufficientBalanceException extends Exception {public InsufficientBalanceException(String message) {super(message);}
}class BankAccount {private double balance;public void withdraw(double amount) throws InsufficientBalanceException {if (amount > balance) {throw new InsufficientBalanceException("余额不足,当前余额: " + balance);}balance -= amount;}
}

五、集合框架

常用集合类

import java.util.*;public class CollectionDemo {public static void main(String[] args) {// List接口 - 有序可重复List<String> arrayList = new ArrayList<>();arrayList.add("Apple");arrayList.add("Banana");arrayList.add("Apple");  // 允许重复
        List<String> linkedList = new LinkedList<>();linkedList.add("Cat");linkedList.add("Dog");// Set接口 - 无序不重复Set<String> hashSet = new HashSet<>();hashSet.add("Red");hashSet.add("Green");hashSet.add("Red");  // 不会重复添加
        Set<String> treeSet = new TreeSet<>();treeSet.add("Zoo");treeSet.add("Apple");treeSet.add("Banana");// 自动排序: [Apple, Banana, Zoo]// Map接口 - 键值对Map<String, Integer> hashMap = new HashMap<>();hashMap.put("Alice", 25);hashMap.put("Bob", 30);hashMap.put("Alice", 26);  // 更新值
        Map<String, Integer> treeMap = new TreeMap<>();treeMap.put("Orange", 5);treeMap.put("Apple", 3);treeMap.put("Banana", 7);// 按键排序: {Apple=3, Banana=7, Orange=5}// 遍历集合for (String fruit : arrayList) {System.out.println(fruit);}for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {System.out.println(entry.getKey() + ": " + entry.getValue());}}
}

六、输入输出流

文件操作

import java.io.*;
import java.nio.file.*;public class IODemo {public static void main(String[] args) {// 使用File类File file = new File("test.txt");try {// 创建文件if (file.createNewFile()) {System.out.println("文件创建成功");}// 写入文件FileWriter writer = new FileWriter(file);writer.write("Hello Java IO\n");writer.write("这是第二行");writer.close();// 读取文件FileReader reader = new FileReader(file);BufferedReader bufferedReader = new BufferedReader(reader);String line;while ((line = bufferedReader.readLine()) != null) {System.out.println(line);}bufferedReader.close();} catch (IOException e) {e.printStackTrace();}// 使用NIO (Java 7+)try {Path path = Paths.get("test_nio.txt");Files.write(path, Arrays.asList("第一行", "第二行", "第三行"),StandardCharsets.UTF_8);List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);for (String text : lines) {System.out.println(text);}} catch (IOException e) {e.printStackTrace();}}
}

七、多线程编程

线程创建与同步

public class ThreadDemo {public static void main(String[] args) {// 继承Thread类MyThread thread1 = new MyThread();thread1.start();// 实现Runnable接口Thread thread2 = new Thread(new MyRunnable());thread2.start();// 使用Lambda表达式Thread thread3 = new Thread(() -> {for (int i = 0; i < 5; i++) {System.out.println("Lambda线程: " + i);}});thread3.start();// 线程同步示例Counter counter = new Counter();Thread t1 = new Thread(() -> {for (int i = 0; i < 1000; i++) {counter.increment();}});Thread t2 = new Thread(() -> {for (int i = 0; i < 1000; i++) {counter.increment();}});t1.start();t2.start();try {t1.join();t2.join();} catch (InterruptedException e) {e.printStackTrace();}System.out.println("最终计数: " + counter.getCount());}
}class MyThread extends Thread {@Overridepublic void run() {for (int i = 0; i < 5; i++) {System.out.println("继承Thread: " + i);}}
}class MyRunnable implements Runnable {@Overridepublic void run() {for (int i = 0; i < 5; i++) {System.out.println("实现Runnable: " + i);}}
}// 线程安全计数器
class Counter {private int count = 0;public synchronized void increment() {count++;}public int getCount() {return count;}
}

八、Java新特性

Java 8+ 重要特性

import java.util.*;
import java.util.stream.*;
import java.time.*;public class NewFeatures {public static void main(String[] args) {// Lambda表达式List<String> names = Arrays.asList("Alice", "Bob", "Charlie");// 传统方式Collections.sort(names, new Comparator<String>() {@Overridepublic int compare(String a, String b) {return a.compareTo(b);}});// Lambda方式Collections.sort(names, (a, b) -> a.compareTo(b));// Stream APIList<String> filteredNames = names.stream().filter(name -> name.startsWith("A")).map(String::toUpperCase).collect(Collectors.toList());System.out.println(filteredNames);  // [ALICE]// 方法引用
        names.forEach(System.out::println);// Optional类 - 避免空指针异常Optional<String> optionalName = Optional.ofNullable(getName());String result = optionalName.orElse("默认名称");System.out.println(result);// 新的日期时间APILocalDate today = LocalDate.now();LocalTime now = LocalTime.now();LocalDateTime currentDateTime = LocalDateTime.now();System.out.println("今天: " + today);System.out.println("现在: " + now);System.out.println("当前日期时间: " + currentDateTime);// 日期计算LocalDate nextWeek = today.plusWeeks(1);Period period = Period.between(today, nextWeek);System.out.println("下周: " + nextWeek);System.out.println("间隔: " + period.getDays() + "天");}private static String getName() {return Math.random() > 0.5 ? "张三" : null;}
}

Java的世界博大精深,基础扎实才能在编程道路上走得更远。希望这篇复盘文章能帮助你巩固Java基础,为后续的深入学习打下坚实基础!

http://www.hskmm.com/?act=detail&tid=37273

相关文章:

  • 【STM32H743IIT6 系列】通过 LTDC接口驱动的 TFTLCD(RGB屏)显示
  • 报表过滤框设置默认组织提示死循环
  • 第九章-NOP Team dmz-C
  • 高级语言设计第二次作业
  • UiPath License
  • 基于伪距差分定位技术实现方案
  • vue项目浏览器内存不断增加
  • 一些变换
  • ANOMALYCLIP
  • AI 辅助开发工具
  • Go开发者必备:5款提升代码质量的顶级Linter工具
  • 函数作用域在解决 JavaScript 自定义元素类跨环境兼容问题中的应用
  • React-router v6学生管理系统笔记 - 教程
  • 2025 年东莞石排到南通物流专线公司最新推荐榜:聚焦企业专利技术、品质管控及知名客户合作案例的权威解析
  • 钡铼技术预测:未来工业AI发展的七大趋势
  • 2025 年废气处理设备厂家最新推荐榜:聚焦企业专利技术、品质管控及知名客户合作案例的权威解析
  • 2025年国产助听器品牌推荐榜:聚焦专业适配,杭州爱听科技引领国产助听新体验​
  • 2025 年PPR家装管厂家最新推荐榜:聚焦企业专利技术、品质管控及知名客户合作案例的权威解析
  • 2025 年连接器厂家最新推荐榜单:聚焦电子 / Type-C / 板对板等品类,精选领军企业助力下游企业精准选型
  • 2025 年干燥机厂家最新推荐排行榜:聚焦闪蒸 / 气流 / 沸腾 / 闭路循环等多类型设备,精选优质企业深度解析
  • 2025 年北京订制旅游 / 精品旅游 / 旅游包车 / 精品小包团旅游旅行社推荐,北京汇通清源国际旅游公司专业服务解析
  • 2025 年北京品牌设计公司最新推荐榜,聚焦企业专业能力与服务价值深度剖析
  • 2025 年报警器经销商最新推荐排行榜:深度解析优质服务商,海湾 / 青鸟 / 利达等品牌优选,郑州安创消防实力领衔
  • 2025 年最新推荐!滑石粉厂家实力排行榜,超细 / 塑料级 / 涂料级 / 造纸级 / 工业级等多类型产品优质企业全解析
  • Linux的基本操作值vi操作对与文件
  • 2025 年最新推荐灭火器维修公司权威榜单:覆盖干粉 / 水基 / 二氧化碳 / 七氟丙烷 / 锂电池灭火器维修,帮您选出专业可靠服务单位
  • 连续与间断
  • 记一次 .NET 某光放测试系统 崩溃分析
  • cookie和缓存的区别
  • 【内网渗透】第168天:基石框架篇单域架构域内应用控制成员组成用户策略信息收集环境搭建