Java编程基础:从语法到面向对象全面解析

发布时间:2026/7/18 2:01:43
Java编程基础:从语法到面向对象全面解析 1. Java基础语法概述Java作为一门面向对象的编程语言其基础语法构成了整个Java编程体系的根基。对于初学者而言掌握这些基础概念就像建造房屋前需要打好地基一样重要。Java的基础语法主要包括以下几个方面程序结构Java程序由类(class)组成每个类包含变量和方法数据类型Java是强类型语言所有变量都必须先声明类型后使用运算符包括算术、关系、逻辑、位运算等多种运算符流程控制if-else、switch、for、while等控制语句数组用于存储同类型数据的集合注释单行注释、多行注释和文档注释三种形式Java程序的基本单位是类每个Java程序至少包含一个类。最简单的Java程序如下public class HelloWorld { public static void main(String[] args) { System.out.println(Hello, World!); } }这个简单的程序展示了Java的几个基本特点类名与文件名必须一致这里是HelloWorld.javamain方法是程序的入口点System.out.println用于输出内容到控制台2. Java基本数据类型与变量2.1 基本数据类型Java有8种基本数据类型分为4大类类型数据类型大小取值范围默认值整型byte1字节-128 ~ 1270short2字节-32768 ~ 327670int4字节-2^31 ~ 2^31-10long8字节-2^63 ~ 2^63-10L浮点型float4字节约±3.4E386-7位有效数字0.0fdouble8字节约±1.7E30815位有效数字0.0d字符型char2字节Unicode字符\u0000~\uffff\u0000布尔型boolean未明确定义true/falsefalse注意Java中默认的整数类型是int如果要定义为long需要在数值后加L或l默认的浮点型是double定义float需要在数值后加F或f。2.2 变量声明与初始化变量是存储数据的基本单元Java中变量声明的基本语法是数据类型 变量名 [ 初始值];例如int age 25; // 声明并初始化整型变量 double price 99.95; // 声明并初始化双精度浮点变量 char grade A; // 声明并初始化字符变量 boolean isPass true; // 声明并初始化布尔变量Java变量命名需要遵循以下规则由字母、数字、下划线(_)和美元符($)组成不能以数字开头不能是Java关键字区分大小写良好的变量命名习惯类名首字母大写驼峰式如StudentInfo方法名和变量名首字母小写驼峰式如getStudentName常量全部大写单词间用下划线连接如MAX_VALUE3. Java运算符与表达式3.1 算术运算符Java提供基本的算术运算符运算符描述示例加法a b-减法a - b*乘法a * b/除法a / b%取模a % b自增a 或 a--自减a-- 或 --a自增/自减运算符的前置和后置区别int a 5; int b a; // b5, a6后置先赋值再自增 int c a; // c7, a7前置先自增再赋值3.2 关系运算符关系运算符用于比较两个值返回布尔结果运算符描述示例等于a b!不等于a ! b大于a b小于a b大于等于a b小于等于a b3.3 逻辑运算符逻辑运算符用于布尔表达式运算运算符描述示例逻辑与a b||逻辑或a || b!逻辑非!a短路特性对于如果左边为false右边不再计算对于||如果左边为true右边不再计算3.4 赋值运算符基本的赋值运算符是还有复合赋值运算符运算符示例等价于a ba a b-a - ba a - b*a * ba a * b/a / ba a / b%a % ba a % b3.5 位运算符位运算符直接操作整数类型的二进制位运算符描述示例按位与a b|按位或a | b^按位异或a ^ b~按位取反~a左移a b右移a b无符号右移a b移位运算符示例int a 8; // 二进制 1000 int b a 2; // 左移2位100000 32 int c a 1; // 右移1位100 44. Java流程控制4.1 条件语句if-else语句基本语法if (条件表达式) { // 条件为true时执行的代码 } else { // 条件为false时执行的代码 }多条件判断if (score 90) { System.out.println(优秀); } else if (score 80) { System.out.println(良好); } else if (score 60) { System.out.println(及格); } else { System.out.println(不及格); }switch-case语句适用于多分支选择switch (表达式) { case 值1: // 代码块1 break; case 值2: // 代码块2 break; ... default: // 默认代码块 }示例int day 3; switch (day) { case 1: System.out.println(星期一); break; case 2: System.out.println(星期二); break; // ...其他case default: System.out.println(无效的天数); }注意从Java 7开始switch支持String类型从Java 12开始支持更简洁的switch表达式语法。4.2 循环结构for循环基本语法for (初始化; 条件; 迭代) { // 循环体 }示例// 打印1到10 for (int i 1; i 10; i) { System.out.println(i); } // 增强for循环foreach int[] numbers {1, 2, 3, 4, 5}; for (int num : numbers) { System.out.println(num); }while循环基本语法while (条件) { // 循环体 }示例int count 0; while (count 5) { System.out.println(Count is: count); count; }do-while循环基本语法do { // 循环体 } while (条件);与while的区别do-while至少执行一次循环体示例int x 10; do { System.out.println(x x); x; } while (x 5); // 虽然条件不满足但会先执行一次4.3 跳转语句break跳出当前循环或switch语句continue跳过当前循环的剩余部分进入下一次循环return从方法中返回可带返回值带标签的break和continueouter: for (int i 0; i 5; i) { inner: for (int j 0; j 5; j) { if (j 3) { break outer; // 直接跳出外层循环 } System.out.println(i i , j j); } }5. Java数组5.1 数组声明与初始化数组是存储同类型数据的集合有以下几种初始化方式// 方式1声明后初始化 int[] arr1; arr1 new int[5]; // 长度为5的int数组默认值0 // 方式2声明时初始化 int[] arr2 new int[]{1, 2, 3, 4, 5}; // 方式3简写形式 int[] arr3 {1, 2, 3, 4, 5}; // 二维数组 int[][] matrix { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };5.2 数组操作常用数组操作// 获取数组长度 int length arr3.length; // 访问数组元素 int first arr3[0]; // 第一个元素 int last arr3[arr3.length - 1]; // 最后一个元素 // 遍历数组 for (int i 0; i arr3.length; i) { System.out.println(arr3[i]); } // 使用foreach遍历 for (int num : arr3) { System.out.println(num); } // 数组排序 Arrays.sort(arr3); // 数组复制 int[] copy Arrays.copyOf(arr3, arr3.length);5.3 数组常见问题数组越界访问不存在的索引会抛出ArrayIndexOutOfBoundsExceptionint[] arr new int[3]; System.out.println(arr[3]); // 错误有效索引是0-2空指针异常未初始化的数组变量为null访问会抛出NullPointerExceptionint[] arr; System.out.println(arr[0]); // 错误arr未初始化数组长度固定创建后长度不可变需要扩容时需创建新数组并复制元素6. Java方法与参数传递6.1 方法定义方法的基本语法[修饰符] 返回类型 方法名([参数列表]) { // 方法体 [return 返回值;] }示例// 无返回值方法 public void printMessage(String msg) { System.out.println(消息 msg); } // 有返回值方法 public int add(int a, int b) { return a b; } // 可变参数方法 public double average(int... numbers) { int sum 0; for (int num : numbers) { sum num; } return (double) sum / numbers.length; }6.2 方法调用方法调用示例printMessage(Hello); // 调用无返回值方法 int result add(3, 5); // 调用有返回值方法 double avg average(1, 2, 3, 4, 5); // 调用可变参数方法6.3 参数传递机制Java中参数传递是值传递基本类型传递的是值的副本引用类型传递的是引用的副本对象地址的副本示例说明// 基本类型参数传递 void changePrimitive(int x) { x 100; } int num 50; changePrimitive(num); System.out.println(num); // 输出50原始值未改变 // 引用类型参数传递 void changeReference(int[] arr) { arr[0] 100; } int[] array {1, 2, 3}; changeReference(array); System.out.println(array[0]); // 输出100数组内容被修改7. Java面向对象基础7.1 类与对象类定义示例public class Person { // 字段成员变量 private String name; private int age; // 构造方法 public Person(String name, int age) { this.name name; this.age age; } // 方法 public void introduce() { System.out.println(我叫 name 今年 age 岁。); } // Getter和Setter public String getName() { return name; } public void setName(String name) { this.name name; } // 其他方法... }创建对象Person p1 new Person(张三, 25); p1.introduce();7.2 构造方法构造方法特点方法名与类名相同没有返回类型连void也没有可以重载多个不同参数的构造方法示例public class Book { private String title; private String author; private double price; // 无参构造方法 public Book() { this(未知, 未知, 0.0); } // 带参构造方法 public Book(String title, String author, double price) { this.title title; this.author author; this.price price; } // 其他方法... }7.3 封装与访问控制Java提供四种访问修饰符修饰符同类同包子类不同包public√√√√protected√√√×default√√××private√×××封装示例public class Student { private String name; // 私有字段外部不能直接访问 private int score; // 通过公共方法访问私有字段 public String getName() { return name; } public void setName(String name) { if (name null || name.trim().isEmpty()) { throw new IllegalArgumentException(姓名不能为空); } this.name name; } // 其他方法... }8. Java常用类8.1 String类String是不可变字符序列常用方法String str Hello, Java!; // 获取长度 int len str.length(); // 字符串连接 String newStr str.concat( Welcome!); // 字符串比较 boolean isEqual str.equals(hello, java!); // false区分大小写 boolean isEqualIgnoreCase str.equalsIgnoreCase(hello, java!); // true // 子字符串 String sub str.substring(7); // Java! String sub2 str.substring(7, 11); // Java // 查找 int index str.indexOf(Java); // 7 boolean contains str.contains(Java); // true // 替换 String replaced str.replace(Java, World); // 分割 String[] parts one,two,three.split(,); // 去除空格 String trimmed hello .trim();8.2 StringBuilder和StringBuffer可变字符序列适用于频繁修改字符串的场景// StringBuilder非线程安全性能更高 StringBuilder sb new StringBuilder(); sb.append(Hello); sb.append( ); sb.append(World); String result sb.toString(); // Hello World // StringBuffer线程安全 StringBuffer sbf new StringBuffer(); sbf.append(Java); sbf.insert(0, Hello ); String result2 sbf.toString(); // Hello Java8.3 Math类提供常用数学运算方法// 绝对值 int abs Math.abs(-10); // 10 // 最大值/最小值 int max Math.max(5, 10); // 10 int min Math.min(5, 10); // 5 // 幂运算 double pow Math.pow(2, 3); // 8.0 // 平方根 double sqrt Math.sqrt(16); // 4.0 // 四舍五入 long round Math.round(3.6); // 4 // 随机数 [0.0, 1.0) double random Math.random(); // 三角函数 double sin Math.sin(Math.PI / 2); // 1.09. Java异常处理9.1 异常分类Java异常体系ThrowableError系统错误应用程序通常不处理如OutOfMemoryErrorException应用程序可以处理的异常RuntimeException运行时异常如NullPointerException其他Exception检查异常如IOException9.2 try-catch-finally基本语法try { // 可能抛出异常的代码 } catch (异常类型1 e) { // 处理异常类型1 } catch (异常类型2 e) { // 处理异常类型2 } finally { // 无论是否发生异常都会执行的代码 }示例try { int result 10 / 0; // 抛出ArithmeticException } catch (ArithmeticException e) { System.out.println(除数不能为零: e.getMessage()); } finally { System.out.println(这段代码总是会执行); }9.3 throw和throwsthrow在方法内部抛出异常对象throws在方法声明中指定可能抛出的异常类型示例// 抛出异常 public void checkAge(int age) { if (age 0) { throw new IllegalArgumentException(年龄不能为负数); } } // 声明可能抛出的异常 public void readFile(String path) throws IOException { // 读取文件操作... }9.4 自定义异常创建自定义异常类// 继承Exception或RuntimeException public class MyException extends Exception { public MyException(String message) { super(message); } public MyException(String message, Throwable cause) { super(message, cause); } } // 使用自定义异常 public void doSomething(int value) throws MyException { if (value 0) { throw new MyException(值不能为负数); } // 其他操作... }10. Java集合框架基础10.1 List接口有序、可重复的集合常用实现类ArrayList基于动态数组随机访问快插入删除慢LinkedList基于链表插入删除快随机访问慢示例ListString arrayList new ArrayList(); arrayList.add(Java); arrayList.add(Python); arrayList.add(C); // 遍历 for (String lang : arrayList) { System.out.println(lang); } // 使用索引访问 String first arrayList.get(0); ListString linkedList new LinkedList(); linkedList.add(Apple); linkedList.add(Banana); linkedList.addFirst(Orange); // 在开头添加10.2 Set接口无序、不重复的集合常用实现类HashSet基于哈希表无序LinkedHashSet保持插入顺序TreeSet基于红黑树有序示例SetInteger hashSet new HashSet(); hashSet.add(10); hashSet.add(20); hashSet.add(10); // 重复元素不会被添加 SetString treeSet new TreeSet(); treeSet.add(Java); treeSet.add(Python); treeSet.add(C); // 自动按字母顺序排序10.3 Map接口键值对集合常用实现类HashMap基于哈希表无序LinkedHashMap保持插入顺序TreeMap基于红黑树按键排序示例MapString, Integer hashMap new HashMap(); hashMap.put(Java, 20); hashMap.put(Python, 15); hashMap.put(C, 10); // 获取值 int javaCount hashMap.get(Java); // 遍历 for (Map.EntryString, Integer entry : hashMap.entrySet()) { System.out.println(entry.getKey() : entry.getValue()); } MapString, Integer treeMap new TreeMap(); treeMap.put(Orange, 5); treeMap.put(Apple, 10); treeMap.put(Banana, 8); // 按键字母顺序排序11. Java I/O基础11.1 文件操作File类示例File file new File(test.txt); // 检查文件是否存在 if (file.exists()) { System.out.println(文件大小: file.length() 字节); // 删除文件 boolean deleted file.delete(); if (deleted) { System.out.println(文件已删除); } } else { // 创建新文件 try { boolean created file.createNewFile(); if (created) { System.out.println(文件创建成功); } } catch (IOException e) { e.printStackTrace(); } }11.2 字节流FileInputStream和FileOutputStream示例// 写入文件 try (FileOutputStream fos new FileOutputStream(data.bin)) { fos.write(Hello Java.getBytes()); } catch (IOException e) { e.printStackTrace(); } // 读取文件 try (FileInputStream fis new FileInputStream(data.bin)) { byte[] buffer new byte[1024]; int bytesRead fis.read(buffer); String content new String(buffer, 0, bytesRead); System.out.println(content); } catch (IOException e) { e.printStackTrace(); }11.3 字符流FileReader和FileWriter示例// 写入文件 try (FileWriter writer new FileWriter(text.txt)) { writer.write(Hello Java\n); writer.write(这是第二行); } catch (IOException e) { e.printStackTrace(); } // 读取文件 try (FileReader reader new FileReader(text.txt)) { char[] buffer new char[1024]; int charsRead reader.read(buffer); String content new String(buffer, 0, charsRead); System.out.println(content); } catch (IOException e) { e.printStackTrace(); }11.4 缓冲流BufferedReader和BufferedWriter示例// 写入文件带缓冲 try (BufferedWriter bw new BufferedWriter(new FileWriter(buffered.txt))) { bw.write(第一行); bw.newLine(); bw.write(第二行); } catch (IOException e) { e.printStackTrace(); } // 读取文件带缓冲 try (BufferedReader br new BufferedReader(new FileReader(buffered.txt))) { String line; while ((line br.readLine()) ! null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); }12. Java枚举与注解12.1 枚举类型枚举定义示例public enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } // 使用枚举 Day today Day.MONDAY; if (today Day.SATURDAY || today Day.SUNDAY) { System.out.println(周末愉快); } else { System.out.println(工作日加油); }带属性的枚举public enum Planet { MERCURY(3.303e23, 2.4397e6), VENUS(4.869e24, 6.0518e6), EARTH(5.976e24, 6.37814e6); private final double mass; // 质量(kg) private final double radius; // 半径(m) Planet(double mass, double radius) { this.mass mass; this.radius radius; } public double surfaceGravity() { return 6.67300E-11 * mass / (radius * radius); } }12.2 注解Java内置常用注解Override表示方法覆盖父类方法Deprecated表示方法已过时SuppressWarnings抑制编译器警告自定义注解// 定义注解 Retention(RetentionPolicy.RUNTIME) Target(ElementType.METHOD) public interface Test { String description() default ; boolean enabled() default true; } // 使用注解 public class MyTest { Test(description 测试方法1, enabled true) public void testMethod1() { // 测试代码 } Test(enabled false) public void testMethod2() { // 这个测试被禁用 } }13. Java泛型13.1 泛型类定义泛型类public class BoxT { private T content; public void setContent(T content) { this.content content; } public T getContent() { return content; } } // 使用泛型类 BoxString stringBox new Box(); stringBox.setContent(Hello); String value stringBox.getContent(); BoxInteger intBox new Box(); intBox.setContent(123); int num intBox.getContent();13.2 泛型方法定义泛型方法public class Util { public static T T getMiddle(T[] array) { return array[array.length / 2]; } } // 使用泛型方法 String[] words {Hello, World, Java}; String middle Util.getMiddle(words); // World Integer[] numbers {1, 2, 3, 4, 5}; int midNum Util.getMiddle(numbers); // 313.3 类型通配符使用通配符增加灵活性public static double sumOfList(List? extends Number list) { double sum 0.0; for (Number num : list) { sum num.doubleValue(); } return sum; } // 可以接受ListInteger, ListDouble等 ListInteger ints Arrays.asList(1, 2, 3); double sum1 sumOfList(ints); ListDouble doubles Arrays.asList(1.1, 2.2, 3.3); double sum2 sumOfList(doubles);14. Java多线程基础14.1 线程创建继承Thread类class MyThread extends Thread { Override public void run() { System.out.println(线程运行: getName()); } } // 创建并启动线程 MyThread thread new MyThread(); thread.start();实现Runnable接口class MyRunnable implements Runnable { Override public void run() { System.out.println(线程运行: Thread.currentThread().getName()); } } // 创建并启动线程 Thread thread new Thread(new MyRunnable()); thread.start();14.2 线程同步使用synchronized关键字class Counter { private int count 0; public synchronized void increment() { count; } public synchronized int getCount() { return count; } } // 使用 Counter counter new Counter(); Runnable task () - { for (int i 0; i 1000; i) { counter.increment(); } }; Thread t1 new Thread(task); Thread t2 new Thread(task); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println(最终计数: counter.getCount()); // 应该是200014.3 线程间通信使用wait()和notify()class Message { private String message; private boolean empty true; public synchronized String read() { while (empty) { try { wait(); } catch (InterruptedException e) {} } empty true; notifyAll(); return message; } public synchronized void write(String message) { while (!empty) { try { wait(); } catch (InterruptedException e) {} } empty false; this.message message; notifyAll(); } }15. Java 8新特性15.1 Lambda表达式Lambda表达式示例// 旧方式匿名内部类 Runnable oldRunnable new Runnable() { Override public void run() { System.out.println(旧方式); } }; // Lambda方式 Runnable newRunnable () - System.out.println(新方式); // 排序示例 ListString names Arrays.asList(Alice, Bob, Charlie); Collections.sort(names, (a, b) - a.compareTo(b));15.2 Stream APIStream操作示例ListString words Arrays.asList(Java, Python, C, JavaScript, Ruby); // 过滤和映射 ListString filtered words.stream() .filter(s - s.startsWith(J)) .map(String::toUpperCase) .collect(Collectors.toList()); // 结果: [JAVA, JAVASCRIPT] // 聚合操作 long count words.stream().filter(s - s.length() 3).count(); OptionalString longest words.stream().max(Comparator.comparingInt(String::length)); // 并行流 int sum words.parallelStream() .mapToInt(String::length) .sum();15.3 Optional类避免NullPointerExceptionOptionalString optional Optional.ofNullable(getString()); // 旧方式 if (optional.isPresent()) { String value optional.get(); System.out.println(value); } // 新方式 optional.ifPresent(System.out::println); // 默认值 String result optional.orElse(默认值); // 链式调用 optional.map(String::toUpperCase) .filter(s - s.length() 3) .ifPresent(System.out::println);16. Java开发常见问题与解决方案16.1 编码问题解决中文乱码// 读取文件时指定编码 try (BufferedReader reader new BufferedReader( new InputStreamReader(new FileInputStream(file.txt), UTF-8))) { // 读取内容 } // 写入文件时指定编码 try (BufferedWriter writer new BufferedWriter( new OutputStreamWriter(new FileOutputStream(file.txt), UTF-8))) { writer.write(中文内容); }16.2 内存管理避免内存泄漏及时关闭资源使用try-with-resources注意集合类中的对象引用避免静态集合长期持有对象合理使用缓存设置大小限制示例// 不好的做法 public class Cache { private static final MapString, Object CACHE new HashMap(); public static void put(String key, Object value) { CACHE.put(key, value); } // 没有移除机制可能导致内存泄漏 } // 改进做法 public class BetterCache { private static final int MAX_SIZE 1000; private static final MapString, Object CACHE new LinkedHashMapString, Object(MAX_SIZE, 0.75f, true) { Override protected boolean removeEldestEntry(Map.Entry eldest) { return size() MAX_SIZE; } }; public static synchronized void put(String key, Object value) { CACHE.put(key, value); } public static synchronized Object get(String key) { return CACHE.get(key); } }16.3 性能优化常见性能优化技巧使用StringBuilder代替字符串拼接合理使用集合类根据场景选择ArrayList/LinkedListHashMap/TreeMap等避免不必要的对象创建使用基本类型而非包装类如int而非Integer合理使用缓存示例// 不好的做法 - 字符串拼接 String result ; for (int i 0; i 100; i) { result i; // 每次循环都创建新的String对象 } // 好的做法 - 使用StringBuilder StringBuilder sb new StringBuilder(); for (int i 0; i 100; i) { sb.append(i); } String result sb.toString();16.4 并发问题常见并发问题及解决方案竞态条件使用同步机制synchronized, Lock死锁避免嵌套锁按固定顺序获取锁内存可见性使用volatile或同步机制线程安全集合使用ConcurrentHashMap, CopyOnWriteArrayList等示例// 使用ConcurrentHashMap替代同步的HashMap ConcurrentMapString, Integer map new ConcurrentHashMap(); // 线程安全的递增操作 map.compute(counter, (k, v) - v null ? 1 : v 1