三天急速通关JAVA基础知识:Day1 基本语法
- 0 文章说明
- 1 关键字 Keywords
- 2 注释 Comments
- 2.1 单行注释
- 2.2 多行注释
- 2.3 文档注释
 
- 3 数据类型 Data Types
- 3.1 基本数据类型
- 3.2 引用数据类型
 
- 4 变量与常量 Variables and Constant
- 5 运算符 Operators
- 6 字符串 String
- 7 输入与输出 Input and Output
- 标准输出(System.out)
 
 
 
- 8 流程控制 Control Flow
- 9 大数 Big Numbers
- 10 数组 Arrays
- Final 考试
0 文章说明
本文目的是为了建立Java的基础知识体系,参考《Core Java, Volume I:Fundamentals》第十二版的第三章目录结构组织,内容由本人已学习的java知识为基础,kimi与gpt辅助完善。本文所提供的信息和内容仅供参考,作者和发布者不保证其准确性和完整性。
1 关键字 Keywords
Java关键字是Java语言的保留字,不能作为变量名、方法名、类名等标识符使用。下面列出经典的关键字,具体示例本篇不给出:
| abstract | assert | boolean | break | byte | 
| case | catch | char | class | const | 
| continue | default | do | double | else | 
| enum | extends | final | finally | float | 
| for | goto | if | implements | import | 
| instanceof | int | interface | long | native | 
| new | package | private | protected | public | 
| return | short | static | strictfp | super | 
| switch | synchronized | this | throw | throws | 
| transient | try | void | volatile | while | 
比较陌生的:
-  assert:用于断言,是一种调试手段,检查程序中的某个条件是否为真。如果条件为假,会抛出 AssertionError异常。
-  default:在 switch语句中表示默认情况,当没有任何case匹配时执行。在接口中,从Java 8开始,可以用于定义默认方法,为接口提供默认实现。
-  finally:用于异常处理, finally块中的代码无论是否捕获到异常都会执行。通常用于资源清理,如关闭文件流、数据库连接等。
-  instanceof:用于判断一个对象是否是某个类或其子类的实例,返回一个布尔值。常用于类型检查和类型转换。 
-  native:用于修饰方法,表示该方法是本地方法,即方法的实现不在Java代码中,而是在其他语言(如C或C++)中实现。通常用于调用底层系统资源或性能敏感的操作。 
-  strictfp:用于修饰方法或类,表示该方法或类中的浮点运算必须严格遵循IEEE 754标准。这可以确保浮点运算在不同平台上具有相同的精度和结果。 
-  synchronized:用于修饰方法或代码块,表示该方法或代码块是同步的,可以用于实现线程同步,防止多个线程同时访问共享资源。 
-  transient:用于修饰变量,表示该变量在对象序列化时不会被序列化。通常用于表示不需要持久化的临时数据。 
-  volatile:用于修饰变量,表示该变量的值可能会被多个线程同时访问和修改,对变量的读写操作需要保证可见性和禁止指令重排序。通常用于多线程环境中的变量共享。 
2 注释 Comments
2.1 单行注释
- 语法://
- 说明:单行注释从//开始,直到该行末尾。推荐在被注释语句上方另起一行
- 示例:// 这是一个单行注释 int x = 10; // 这是变量x的声明和初始化
2.2 多行注释
- 语法:/*和*/
- 说明:多行注释从/*开始,到*/结束,可以跨越多行。
- 示例:/** 这是一个多行注释* 可以包含多行文本* 用于对代码块进行详细说明*/int y = 20;
2.3 文档注释
- 语法:/**和*/
- 说明:多行注释从/**开始,到*/结束,通常用于生成API文档。它主要用于类、接口、方法和字段的文档化。文档注释可以被javadoc工具解析,生成HTML格式的文档。
- 示例:/*** 这是一个文档注释* 用于生成API文档* @param x 输入参数* @return 返回值*/public int add(int x, int y) {return x + y;}
3 数据类型 Data Types
Java的数据类型主要分为两大类:基本数据类型和引用数据类型。
3.1 基本数据类型
包括整数类型(byte、short、int、long)、浮点类型(float、double)、字符类型(char)和布尔类型(boolean)。
| 类型 | 大小(位) | 默认值 | 范围 | 
|---|---|---|---|
| byte | 8 | 0 | -128 到 127 | 
| short | 16 | 0 | -32,768 到 32,767 | 
| int | 32 | 0 | -2³¹ 到 2³¹-1 | 
| long | 64 | 0L | -2⁶³ 到 2⁶³-1 | 
| float | 32 | 0.0f | 约 ±3.40282347E+38F | 
| double | 64 | 0.0d | 约 ±1.79769313486231570E+308 | 
| char | 16 | ‘\u0000’ | 单个字符(支持 Unicode 编码) | 
| boolean | 不固定 | false | 仅能取值 true或false | 
3.2 引用数据类型
引用数据类型在 Java 中是用于存储对象的内存地址,而不是直接存储数据值。引用类型主要包括 类(Class)、接口(Interface)、数组(Array) 和 枚举(Enum)。它们允许更复杂的数据结构和行为的定义。
-  类(Class) 
 类是创建对象的模板,包含属性和方法。对象是类的实例。class Person {String name;int age;void sayHello() {System.out.println("Hello, my name is " + name);} } // 使用类创建对象 Person person = new Person(); person.name = "Alice"; person.age = 25; person.sayHello(); // 输出: Hello, my name is Alice
-  接口(Interface) 
 接口是行为的规范,定义了一组抽象方法。实现接口的类必须提供这些方法的具体实现。interface Animal {void makeSound(); }class Dog implements Animal {public void makeSound() {System.out.println("Woof!");} } // 使用接口 Animal dog = new Dog(); dog.makeSound(); // 输出: Woof!
-  数组(Array) 
 数组是存储相同类型元素的集合,长度固定。int[] numbers = {1, 2, 3, 4, 5}; System.out.println(numbers[2]); // 输出: 3String[] names = {"Alice", "Bob", "Charlie"}; System.out.println(names[0]); // 输出: Alice
-  枚举(Enum) 
 枚举是一个特殊的类,用于定义一组固定的常量。enum Day {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }// 使用枚举 Day today = Day.WEDNESDAY; System.out.println(today); // 输出: WEDNESDAY
-  注解(Annotations 
 注解用于提供元数据,可以用于类、方法、字段等。注解可以被编译器、运行时环境或其他工具读取和处理。public @interface MyAnnotation {String value(); }@MyAnnotation("Hello") public class MyClass { }
4 变量与常量 Variables and Constant
根据位置不同,分为不同类型的变量与常量,有哪些位置呢?方法中,类中以及类中用static修饰了,就这三种情况,分别就是局部,实例以及类(静态) 变量或常量。
| 类型 | 说明 | 示例 | 
|---|---|---|
| 变量 | 存储数据的容器,具有类型、名称和值。 | int age = 25; | 
| 局部变量 | 在方法或代码块中定义的变量,只在该方法或代码块中有效。 | public void myMethod() { int localVar = 10; } | 
| 实例变量 | 在类中定义的变量,属于类的实例,每个对象都有自己的实例变量。 | public class Person { String name; int age; } | 
| 类变量 | 在类中定义的静态变量,属于类本身,所有对象共享同一个类变量。 | public class Person { static String species = "Homo sapiens"; } | 
| 常量 | 值在程序运行期间不会改变的变量,通常使用 final关键字修饰。 | final double PI = 3.14159; | 
| 实例常量 | 属于类的实例,每个对象都有自己的实例常量。 | public class Person { final String species = "Homo sapiens"; } | 
| 类常量 | 属于类本身,所有对象共享同一个类常量。 | public class Person { static final String species = "Homo sapiens"; } | 
变量和常量中容易出错的点:
-  变量类型不匹配 - 类型不兼容的赋值:将不同类型的变量赋值给一个变量时,需要进行显式的类型转换,或者使用正确的类型。int a = 10; double b = 3.14; a = b; // 错误:类型不兼容,必须显式转换 a = (int) b; // 正确:类型转换
 
- 类型不兼容的赋值:将不同类型的变量赋值给一个变量时,需要进行显式的类型转换,或者使用正确的类型。
-  常量定义 - 常量初始化:常量必须在声明时初始化,否则会引发编译错误。final int MAX_VALUE; // 错误:常量必须初始化 MAX_VALUE = 100; // 错误:常量只能赋值一次
 
- 常量初始化:常量必须在声明时初始化,否则会引发编译错误。
-  常量修改 - 不能修改常量值:常量被声明后值不可更改,尝试修改常量会引发编译错误。final int MAX_VALUE = 100; MAX_VALUE = 200; // 错误:常量的值不能被修改
 
- 不能修改常量值:常量被声明后值不可更改,尝试修改常量会引发编译错误。
-  常量命名 - 常量命名规范:常量通常应使用全大写字母,并使用下划线分隔词。final int MaxValue = 100; // 不符合规范,应该使用 MAX_VALUE final int MAX_VALUE = 100; // 正确
 
- 常量命名规范:常量通常应使用全大写字母,并使用下划线分隔词。
-  变量作用域 - 局部变量与全局变量冲突:如果局部变量和类字段(成员变量)同名,局部变量会遮蔽类字段。int x = 10; // 类字段 public void method() {int x = 20; // 局部变量,遮蔽类字段System.out.println(x); // 输出 20,而不是类字段的 10 }
 
- 局部变量与全局变量冲突:如果局部变量和类字段(成员变量)同名,
-  静态变量和实例变量 - 静态变量与实例变量的混淆:静态变量属于类,而实例变量属于对象。静态变量应通过类名访问,而实例变量应通过对象访问。class MyClass {static int staticVar = 5;int instanceVar = 10;public static void main(String[] args) {MyClass obj = new MyClass();System.out.println(staticVar); // 正确:可以直接访问静态变量System.out.println(obj.instanceVar); // 正确:通过对象访问实例变量} }
 
- 静态变量与实例变量的混淆:静态变量属于类,而实例变量属于对象。静态变量应通过类名访问,而实例变量应通过对象访问。
-  变量的默认值 - 局部变量未初始化:局部变量没有默认值,必须初始化后才能使用。成员变量有默认值(例如,int类型的成员变量默认为0)。int x; // 错误:局部变量没有默认值,必须初始化
 
- 局部变量未初始化:局部变量没有默认值,必须初始化后才能使用。成员变量有默认值(例如,
-  引用类型变量的默认值 - 引用类型变量默认值为 null:引用类型的变量(如对象类型)默认值为null,如果尝试访问它们的属性或方法,会引发NullPointerException。String str; // 默认值为 null System.out.println(str.length()); // 错误:会抛出 NullPointerException
 
- 引用类型变量默认值为 
5 运算符 Operators
运算符在 Java 中占据着重要的位置,对程序的执行有着很大的帮助。除了常见的加减乘除, 还有许多其他类型的运算符。
| 类别 | 运算符形式 | 说明 | 
|---|---|---|
| 算术运算符 | +, -, *, /, % | 用于执行基本的加、减、乘、除和取余运算。 | 
| ++, - - | 自增和自减运算符,前缀或后缀形式。 | |
| 赋值运算符 | |=, +=, -=, *=, /=, %= | 用于给变量赋值,可结合算术运算符形成复合赋值。 | 
| 关系运算符 | ==, !=, <, >, <=, >= | 比较两个值的关系,返回布尔值 true或false。 | 
| 逻辑运算符 | &&, ||, ! | 用于布尔逻辑运算:逻辑与、逻辑或和逻辑非。 | 
| 位运算符 | &, |, ^, ~ | 位与、位或、位异或、位取反运算符。 | 
| <<, >>, >>> | 位移运算符:左移、右移和无符号右移。 | |
| 条件运算符 | ? : | 三元运算符,根据条件返回不同的值。 | 
| 类型比较运算符 | instanceof | 检查对象是否是某个类的实例。 | 
| 位逻辑赋值运算符 | &=, |=, ^= | 结合位运算和赋值操作。 | 
容易出错的点:
- 取余运算:负数取余时,结果的符号与被除数一致。 - -5 % 3的结果是- -2。
 
- 复合赋值:复合赋值运算符会自动进行类型转换,可能导致数据精度丢失。int a = 5; a += 2.5; // 等价于 a = (int)(a + 2.5),结果为 7
- 浮点数比较:浮点数计算可能会有精度误差,因此直接使用 ==比较可能不准确。- 建议:使用 Math.abs(a - b) < epsilon方法进行比较。
 
- 建议:使用 
- 短路运算:&&和||是短路运算符,可能导致右侧表达式不被执行。boolean result = (x > 5) && (y++ > 2); // 如果 x <= 5,y 不会自增
- 符号扩展:在位移运算中,>>会保留符号位,>>>不保留符号位。int a = -8; System.out.println(a >> 1); // 结果是 -4 System.out.println(a >>> 1); // 结果是一个正数
- 优先级问题:条件运算符 ? :的优先级较低,可能需要加括号以避免误解。int a = 10, b = 5; int result = a > b ? a : b + 10; // 实际等价于 a > b ? a : (b + 10)
- 字符串连接:+运算符在连接字符串时,可能会误解数值操作。System.out.println("Sum: " + 5 + 3); // 输出为 Sum: 53,而不是 Sum: 8
6 字符串 String
在Java中,String 是一个非常重要的类,用于表示和操作字符串。字符串在Java中是不可变的,这意味着一旦创建,其内容就不能被修改。
 常见方法:
| 方法 | 说明 | 示例 | 返回值 | 
|---|---|---|---|
| concat(String str) | 连接两个字符串 | java String s1 = "Hello"; String s2 = s1.concat(" World");  | “Hello World” | 
| +运算符 | 连接两个字符串 | java String s1 = "Hello"; String s2 = s1 + " World";  | “Hello World” | 
| equals(Object anObject) | 比较两个字符串的内容是否相同 | java String s1 = "Hello"; String s2 = "Hello"; boolean isEqual = s1.equals(s2);  | true | 
| equalsIgnoreCase(String anotherString) | 比较两个字符串的内容是否相同,忽略大小写 | java String s1 = "Hello"; String s2 = "hello"; boolean isEqual = s1.equalsIgnoreCase(s2);  | true | 
| == | 比较两个字符串对象是否是同一个对象 | java String s1 = "Hello"; String s2 = "Hello"; boolean isSameObject = s1 == s2;  | true(因为字符串常量池) | 
| indexOf(int ch) | 返回指定字符在字符串中第一次出现的索引 | java String s = "Hello, World!"; int index = s.indexOf('o');  | 4 | 
| lastIndexOf(int ch) | 返回指定字符在字符串中最后一次出现的索引 | java String s = "Hello, World!"; int index = s.lastIndexOf('o');  | 8 | 
| substring(int beginIndex) | 返回从指定索引开始到字符串末尾的子字符串 | java String s = "Hello, World!"; String sub = s.substring(7);  | “World!” | 
| substring(int beginIndex, int endIndex) | 返回从指定开始索引到结束索引的子字符串 | java String s = "Hello, World!"; String sub = s.substring(7, 12);  | “World” | 
| toLowerCase() | 将字符串转换为小写 | java String s = "Hello, World!"; String lower = s.toLowerCase();  | “hello, world!” | 
| toUpperCase() | 将字符串转换为大写 | java String s = "Hello, World!"; String upper = s.toUpperCase();  | “HELLO, WORLD!” | 
| trim() | 去除字符串两端的空白字符 | java String s = " Hello, World! "; String trimmed = s.trim();  | “Hello, World!” | 
| split(String regex) | 根据指定的正则表达式分割字符串,返回一个字符串数组 | java String s = "Hello,World,Java"; String[] parts = s.split(",");  | [“Hello”, “World”, “Java”] | 
一些技巧:
- 字符串比较 - 错误:使用==比较字符串内容。String s1 = "Hello"; String s2 = "hello"; boolean isEqual = s1 == s2; // false(因为字符串常量池)
- 正确做法:使用equals方法比较字符串内容。String s1 = "Hello"; String s2 = "hello"; boolean isEqual = s1.equals(s2); // false
 
- 错误:使用
- 字符串不可变性 - 错误:尝试修改字符串内容。String s = "Hello"; s.concat(" World"); // s 仍然是 "Hello"
- 正确做法:使用新的变量接收修改后的字符串。String s = "Hello"; String newS = s.concat(" World"); // newS 是 "Hello World"
 
- 错误:尝试修改字符串内容。
- 字符串常量池 - 错误:假设所有字符串字面量都会进入字符串常量池。String s1 = "Hello"; String s2 = new String("Hello"); boolean isSameObject = s1 == s2; // false(因为s2是通过new创建的)
- 正确做法:使用intern方法确保字符串进入常量池。String s1 = "Hello"; String s2 = new String("Hello").intern(); boolean isSameObject = s1 == s2; // true
 
- 错误:假设所有字符串字面量都会进入字符串常量池。
- 字符串分割 - 错误:忽略分割后的空字符串。String s = "a,,b,c,,"; String[] parts = s.split(","); // parts 会包含空字符串 ["a", "", "b", "c", "", ""]
- 正确做法:使用正则表达式去除空字符串。String s = "a,,b,c,,"; String[] parts = s.split(",+"); // parts 不会包含空字符串 ["a", "b", "c"]
 
- 错误:忽略分割后的空字符串。
- 字符串连接 - 错误:在循环中使用+连接字符串,导致性能问题。String result = ""; for (int i = 0; i < 1000; i++) {result = result + i; // 每次迭代都会创建新的字符串对象 }
- 正确做法:使用StringBuilder或StringBuffer进行字符串连接。StringBuilder sb = new StringBuilder(); for (int i = 0; i < 1000; i++) {sb.append(i); // 高效的字符串连接 } String result = sb.toString();
 
- 错误:在循环中使用
7 输入与输出 Input and Output
输入和输出(I/O)是程序与用户或其他系统进行交互的重要方式。Java提供了丰富的类和接口来处理输入和输出操作,主要位于java.io包中。下面只介绍基础的输入输出处理:
- Scanner 类 - nextLine():读取一行文本。- Scanner scanner = new Scanner(System.in); System.out.print("Enter your name: "); String name = scanner.nextLine(); // 读取一行文本
- nextInt():读取一个整数。- System.out.print("Enter your age: "); int age = scanner.nextInt(); // 读取一个整数
- nextDouble():读取一个双精度浮点数。- System.out.print("Enter your salary: "); double salary = scanner.nextDouble(); // 读取一个双精度浮点数
- next():读取一个单词(以空白字符分隔的字符串)。- System.out.print("Enter your name: "); String name = scanner.next(); // 读取一个单词
 
标准输出(System.out)
- print 方法 - print(String s):输出一个字符串,不换行。- System.out.print("Hello, "); // 输出字符串,不换行
- print(int i):输出一个整数,不换行。- System.out.print(123); // 输出整数,不换行
- print(double d):输出一个双精度浮点数,不换行。- System.out.print(3.14); // 输出浮点数,不换行
 
- printf 方法 - printf(String format, Object... args):格式化输出。
  - System.out.printf("Hello, %s. You are %d years old.", "John", 30); // 格式化输出
 
易错点:
-  使用 Scanner类- 确保关闭Scanner对象,释放系统资源。
- 捕获InputMismatchException,处理输入错误。
- 在使用nextInt()或nextDouble()后调用nextLine(),清除缓冲区中的换行符。
 
- 确保关闭
-  使用 print和printf方法- 确保格式化字符串中的占位符与实际参数类型匹配。
- 使用println方法或手动添加换行符,确保输出内容格式正确。
- 使用printf方法时,使用%n换行符确保每行输出后换行。
 
8 流程控制 Control Flow
略
9 大数 Big Numbers
Java提供了BigInteger和BigDecimal类来处理这种大数值(超出常规数据类型如int和long范围的数值问题。
- BigInteger类:任意精度的整数运算
| 方法 | 说明 | 示例 | 
|---|---|---|
| BigInteger(String val) | 通过字符串创建BigInteger对象 | BigInteger bigInt1 = new BigInteger("123456789012345678901234567890"); | 
| BigInteger.valueOf(long val) | 通过长整数值创建BigInteger对象 | BigInteger bigInt2 = BigInteger.valueOf(12345678901234567890L); | 
| add(BigInteger val) | 加法 | BigInteger sum = bigInt1.add(bigInt2); | 
| subtract(BigInteger val) | 减法 | BigInteger difference = bigInt1.subtract(bigInt2); | 
| multiply(BigInteger val) | 乘法 | BigInteger product = bigInt1.multiply(bigInt2); | 
| divide(BigInteger val) | 除法 | BigInteger quotient = bigInt1.divide(bigInt2); | 
| mod(BigInteger val) | 取模 | BigInteger remainder = bigInt1.mod(bigInt2); | 
- BigDecimal类:任意精度的浮点数运算
| 方法 | 说明 | 示例 | 
|---|---|---|
| BigDecimal(String val) | 通过字符串创建BigDecimal对象 | BigDecimal bigDecimal1 = new BigDecimal("12345.67890"); | 
| BigDecimal.valueOf(double val) | 通过double值创建BigDecimal对象 | BigDecimal bigDecimal2 = BigDecimal.valueOf(12345.67890); | 
| add(BigDecimal val) | 加法 | BigDecimal sum = bigDecimal1.add(bigDecimal2); | 
| subtract(BigDecimal val) | 减法 | BigDecimal difference = bigDecimal1.subtract(bigDecimal2); | 
| multiply(BigDecimal val) | 乘法 | BigDecimal product = bigDecimal1.multiply(bigDecimal2); | 
| divide(BigDecimal val, int scale, RoundingMode mode) | 除法,指定小数位数和舍入模式 | BigDecimal quotient = bigDecimal1.divide(bigDecimal2, 2, RoundingMode.HALF_UP); | 
Java中BigInteger和BigDecimal类的常见易错点:
-  BigInteger类 
-  使用错误的构造方法 - 错误:使用BigInteger(int signum, byte[] magnitude)构造方法时,传入的参数不正确。byte[] bytes = {1, 2, 3}; BigInteger bigInt = new BigInteger(1, bytes); // 正确 BigInteger bigInt = new BigInteger(-1, bytes); // 负数
- 正确做法:确保signum参数正确,1表示正数,-1表示负数,0表示零。byte[] bytes = {1, 2, 3}; BigInteger bigInt = new BigInteger(1, bytes); // 正确
 
- 错误:使用
-  除法运算未处理异常 - 错误:在进行除法运算时,未处理ArithmeticException。BigInteger bigInt1 = new BigInteger("10"); BigInteger bigInt2 = new BigInteger("0"); BigInteger quotient = bigInt1.divide(bigInt2); // 抛出ArithmeticException
- 正确做法:在进行除法运算时,确保除数不为零,或捕获ArithmeticException。BigInteger bigInt1 = new BigInteger("10"); BigInteger bigInt2 = new BigInteger("0"); try {BigInteger quotient = bigInt1.divide(bigInt2); } catch (ArithmeticException e) {System.out.println("除数不能为零"); }
 
- 错误:在进行除法运算时,未处理
-  使用 intValue、longValue等方法时未处理溢出- 错误:在将BigInteger转换为int或long时,未处理可能的溢出。BigInteger bigInt = new BigInteger("12345678901234567890"); int value = bigInt.intValue(); // 可能溢出
- 正确做法:在转换前,使用bitLength方法检查数值是否在范围内。BigInteger bigInt = new BigInteger("12345678901234567890"); if (bigInt.bitLength() <= 31) {int value = bigInt.intValue(); } else {System.out.println("数值超出int范围"); }
 
- 错误:在将
-  BigDecimal类 
-  使用 double值创建BigDecimal- 错误:使用double值创建BigDecimal,导致精度问题。BigDecimal bigDecimal = new BigDecimal(12345.67890); // 精度问题
- 正确做法:使用字符串创建BigDecimal,避免精度问题。BigDecimal bigDecimal = new BigDecimal("12345.67890"); // 正确
 
- 错误:使用
-  除法运算未处理异常 - 错误:在进行除法运算时,未处理ArithmeticException。BigDecimal bigDecimal1 = new BigDecimal("10"); BigDecimal bigDecimal2 = new BigDecimal("0"); BigDecimal quotient = bigDecimal1.divide(bigDecimal2); // 抛出ArithmeticException
- 正确做法:在进行除法运算时,确保除数不为零,或捕获ArithmeticException。BigDecimal bigDecimal1 = new BigDecimal("10"); BigDecimal bigDecimal2 = new BigDecimal("0"); try {BigDecimal quotient = bigDecimal1.divide(bigDecimal2); } catch (ArithmeticException e) {System.out.println("除数不能为零"); }
 
- 错误:在进行除法运算时,未处理
-  除法运算未指定舍入模式 - 错误:在进行除法运算时,未指定舍入模式,导致ArithmeticException。BigDecimal bigDecimal1 = new BigDecimal("10"); BigDecimal bigDecimal2 = new BigDecimal("3"); BigDecimal quotient = bigDecimal1.divide(bigDecimal2); // 抛出ArithmeticException
- 正确做法:在进行除法运算时,指定舍入模式。BigDecimal bigDecimal1 = new BigDecimal("10"); BigDecimal bigDecimal2 = new BigDecimal("3"); BigDecimal quotient = bigDecimal1.divide(bigDecimal2, 2, RoundingMode.HALF_UP); // 正确
 
- 错误:在进行除法运算时,未指定舍入模式,导致
-  使用 floatValue、doubleValue等方法时未处理精度损失- 错误:在将BigDecimal转换为float或double时,未处理可能的精度损失。BigDecimal bigDecimal = new BigDecimal("12345.67890"); double value = bigDecimal.doubleValue(); // 精度损失
- 正确做法:在转换前,确保数值在范围内,或使用setScale方法调整精度。BigDecimal bigDecimal = new BigDecimal("12345.67890"); BigDecimal scaledValue = bigDecimal.setScale(2, RoundingMode.HALF_UP); double value = scaledValue.doubleValue(); // 正确
 
- 错误:在将
希望这些信息对你有帮助!如果你有任何问题或需要进一步的解释,请随时告诉我。
10 数组 Arrays
- 一维数组
| 方法 | 说明 | 示例 | 
|---|---|---|
| 声明数组 | 声明一个数组,但不初始化 | int[] arr; | 
| 静态初始化 | 在声明数组时直接赋值 | int[] arr = {1, 2, 3, 4, 5}; | 
| 动态初始化 | 指定数组的长度,元素默认初始化 | int[] arr = new int[5]; | 
- 二维数组
| 方法 | 说明 | 示例 | 
|---|---|---|
| 声明和初始化二维数组 | 声明并初始化二维数组 | int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; | 
- 常见方法
| 方法 | 说明 | 示例 | 
|---|---|---|
| length | 获取数组长度 | int len = arr.length; | 
| arr[index] | 访问数组元素 | int element = arr[0]; | 
| arr[index] = value | 修改数组元素 | arr[0] = 10; | 
| Arrays.sort | 排序数组 | Arrays.sort(arr); | 
| Arrays.binarySearch | 查找数组元素 | int index = Arrays.binarySearch(arr, 3); | 
| Arrays.fill | 填充数组 | Arrays.fill(arr, 10); | 
| Arrays.copyOf | 复制数组 | int[] copy = Arrays.copyOf(arr, arr.length); | 
| Arrays.asList | 将数组转换为列表 | List<Integer> list = Arrays.asList(arr); | 
| Arrays.toString | 将数组转换为字符串 | System.out.println(Arrays.toString(arr)); | 
| Arrays.deepToString | 将多维数组转换为字符串 | System.out.println(Arrays.deepToString(matrix)); | 
Final 考试
-  关键字 
 模拟一个动物世界,支持鸟类和哺乳动物的多态行为,并限制某些动物不能被继承或扩展。interface Animal {void makeSound();void move(); }abstract class Bird implements Animal {protected String name;public Bird(String name) {this.name = name;}public abstract void fly();@Overridepublic void move() {System.out.println(name + " is moving.");} }final class Eagle extends Bird {public Eagle(String name) {super(name);}@Overridepublic void makeSound() {System.out.println(name + " screeches!");}@Overridepublic void fly() {System.out.println(name + " is soaring high.");} }class Mammal implements Animal {private String name;public Mammal(String name) {this.name = name;}@Overridepublic void makeSound() {System.out.println(name + " makes a mammal sound.");}@Overridepublic void move() {System.out.println(name + " is walking.");} }public class Main {public static void main(String[] args) {Animal eagle = new Eagle("Golden Eagle");eagle.makeSound();eagle.move();Animal lion = new Mammal("Lion");lion.makeSound();lion.move();} }
-  注释 
 为一个贷款利息计算器编写详细的注释,解释计算步骤和逻辑。/*** 贷款利息计算器* 计算贷款的月还款金额和总利息*/ public class LoanCalculator {/*** 计算月还款金额* @param principal 贷款本金* @param annualRate 年利率(小数形式)* @param months 贷款期数(以月为单位)* @return 每月还款金额*/public double calculateMonthlyPayment(double principal, double annualRate, int months) {double monthlyRate = annualRate / 12; // 月利率return (principal * monthlyRate) / (1 - Math.pow(1 + monthlyRate, -months));}/*** 计算总利息* @param monthlyPayment 每月还款金额* @param months 贷款期数* @param principal 贷款本金* @return 总利息*/public double calculateTotalInterest(double monthlyPayment, int months, double principal) {return (monthlyPayment * months) - principal;}public static void main(String[] args) {LoanCalculator calculator = new LoanCalculator();double principal = 50000; // 本金double annualRate = 0.05; // 年利率int months = 24; // 期数double monthlyPayment = calculator.calculateMonthlyPayment(principal, annualRate, months);double totalInterest = calculator.calculateTotalInterest(monthlyPayment, months, principal);System.out.printf("每月还款金额: %.2f\n", monthlyPayment);System.out.printf("总利息: %.2f\n", totalInterest);} }
-  数据类型 
 模拟一个个人信息管理系统,支持用户输入、修改和打印复杂的个人数据。import java.util.Scanner;public class PersonalInfoManager {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);// 基本数据类型System.out.print("请输入姓名: ");String name = scanner.nextLine();System.out.print("请输入年龄: ");int age = scanner.nextInt();System.out.print("请输入身高 (米): ");float height = scanner.nextFloat();System.out.print("是否已婚 (true/false): ");boolean isMarried = scanner.nextBoolean();// 输出个人信息System.out.println("\n个人信息:");System.out.printf("姓名: %s\n", name);System.out.printf("年龄: %d\n", age);System.out.printf("身高: %.2f 米\n", height);System.out.printf("婚姻状况: %s\n", isMarried ? "已婚" : "未婚");} }
-  变量与常量 
 设计一个动态管理圆的系统,可以根据用户输入动态创建多个圆,并输出总圆数和每个圆的面积。class Circle {private static int totalCircles = 0; // 类变量private double radius; // 实例变量private static final double PI = 3.14159; // 类常量public Circle(double radius) {this.radius = radius;totalCircles++;}public double calculateArea() {return PI * radius * radius;}public static int getTotalCircles() {return totalCircles;} }public class CircleManager {public static void main(String[] args) {Circle c1 = new Circle(3.5);Circle c2 = new Circle(4.2);System.out.printf("圆1的面积: %.2f\n", c1.calculateArea());System.out.printf("圆2的面积: %.2f\n", c2.calculateArea());System.out.println("总圆数: " + Circle.getTotalCircles());} }
-  运算符 public class OperatorsExample {public static void main(String[] args) {int a = 15, b = 5, c = 2;// 使用括号来明确运算优先级int result = (a + b) * c - (b % c);System.out.println("表达式计算结果: " + result);// 复合赋值运算符a += 5; // a = a + 5System.out.println("a 经过复合赋值运算后的值: " + a);// 三目运算符int max = (a > b) ? a : b;System.out.println("a 和 b 中较大的值: " + max);// 自增和自减运算符int preIncrement = ++a; // 先加再使用int postDecrement = b--; // 先使用再减System.out.println("自增后的 a: " + preIncrement);System.out.println("自减后的 b: " + postDecrement);// 逻辑运算符boolean condition = (a > 20) && (b < 10);System.out.println("逻辑运算结果 (a > 20) && (b < 10): " + condition);} }
-  字符串 import java.nio.charset.StandardCharsets; import java.util.regex.Matcher; import java.util.regex.Pattern;public class StringExample {public static void main(String[] args) {String str = "Hello, World! 123 Java";// 字符串拼接String result = str + " - Welcome!";System.out.println("拼接后的字符串: " + result);// 查找某一子字符串int index = str.indexOf("Java");System.out.println("Java 字符串的起始索引: " + index);// 正则表达式匹配String regex = "\\d+"; // 匹配数字Pattern pattern = Pattern.compile(regex);Matcher matcher = pattern.matcher(str);while (matcher.find()) {System.out.println("找到的数字: " + matcher.group());}// 字符串替换String replaced = str.replace("World", "Java");System.out.println("替换后的字符串: " + replaced);// 字符串分割String[] words = str.split(" ");System.out.println("分割后的数组: ");for (String word : words) {System.out.println(word);}// 大小写转换System.out.println("大写字符串: " + str.toUpperCase());System.out.println("小写字符串: " + str.toLowerCase());// 字符编码转换byte[] bytes = str.getBytes(StandardCharsets.UTF_8);String encodedString = new String(bytes, StandardCharsets.UTF_8);System.out.println("编码转换后的字符串: " + encodedString);} }
-  流程控制 
 实现一个科学计算器,支持平方、平方根和阶乘计算。import java.util.Scanner;public class ScientificCalculator {public static double square(double number) {return number * number;}public static double squareRoot(double number) {if (number < 0) {throw new IllegalArgumentException("不能计算负数的平方根!");}return Math.sqrt(number);}public static long factorial(int number) {if (number < 0) {throw new IllegalArgumentException("不能计算负数的阶乘!");}long result = 1;for (int i = 1; i <= number; i++) {result *= i;}return result;}public static void main(String[] args) {Scanner scanner = new Scanner(System.in);while (true) {System.out.print("\n选择操作:1. 平方 2. 平方根 3. 阶乘 4. 退出\n请输入选项:");int choice = scanner.nextInt();if (choice == 4) {System.out.println("退出程序。");break;}System.out.print("请输入一个数字:");double number = scanner.nextDouble();switch (choice) {case 1 -> System.out.printf("平方结果:%.2f\n", square(number));case 2 -> System.out.printf("平方根结果:%.2f\n", squareRoot(number));case 3 -> {int intNumber = (int) number;System.out.printf("阶乘结果:%d\n", factorial(intNumber));}default -> System.out.println("无效选项!");}}} }
-  大数 import java.math.BigInteger; import java.math.BigDecimal;public class BigNumbersExample {public static void main(String[] args) {// BigInteger 示例BigInteger big1 = new BigInteger("9876543210123456789");BigInteger big2 = new BigInteger("1234567890987654321");// 大数加法BigInteger sum = big1.add(big2);System.out.println("大数加法结果: " + sum);// 大数乘法BigInteger product = big1.multiply(big2);System.out.println("大数乘法结果: " + product);// BigDecimal 示例 - 处理精度高的小数BigDecimal decimal1 = new BigDecimal("0.123456789123456789123456789");BigDecimal decimal2 = new BigDecimal("0.987654321987654321987654321");// 小数加法BigDecimal decimalSum = decimal1.add(decimal2);System.out.println("大数小数加法结果: " + decimalSum);// 小数乘法BigDecimal decimalProduct = decimal1.multiply(decimal2);System.out.println("大数小数乘法结果: " + decimalProduct);// 限定小数精度BigDecimal rounded = decimalProduct.setScale(10, BigDecimal.ROUND_HALF_UP);System.out.println("四舍五入后的小数: " + rounded);} }
-  数组 
 实现一个成绩管理系统,支持存储、更新和计算多个学生的平均成绩。import java.util.Scanner;public class GradeManager {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.print("请输入学生人数:");int numStudents = scanner.nextInt();double[] grades = new double[numStudents];for (int i = 0; i < numStudents; i++) {System.out.printf("请输入学生 %d 的成绩:", i + 1);grades[i] = scanner.nextDouble();}double sum = 0;for (double grade : grades) {sum += grade;}double average = sum / numStudents;System.out.printf("所有学生的平均成绩为:%.2f\n", average);} }