java 语法基础
hello world
public class HelloWorld {
public static void main(String[] args) {
// psvm
System.out.println("Hello World!");
}
}
常量与变量
- 常量: 在程序运行过程中,其值不可以发生改变的量。
- 变量: 在程序运行过程中,其值可以发生改变的量。
public class ConstantAndVariable {
public static void main(String[] args) {
// 常量 PI
final double PI = 3.14;
// 变量 数据类型: 整型
int age = 18;
// 变量 数据类型: 字符串
String name = "张三";
// 变量 数据类型: 布尔型
boolean isMale = true;
// 变量 数据类型: 字符型
char a = 'a';
// 变量 数据类型: 字节型
byte b = 127;
// 变量 数据类型: 短整型
short s = 32767;
// 变量 数据类型: 整型
int i = 2147483647;
// 变量 数据类型: 长整型
long l = 9223372036854775807L;
// 变量 数据类型: 单精度浮点型
float f = 3.4028235E38F;
// 变量 数据类型: 双精度浮点型
double d = 1.7976931348623157E308;
}
}
数据类型
基本数据类型
- 整型
- byte
- short
- int
- long
- 浮点型
- float
- double
- 字符型
- char
- 布尔型
- boolean
- 整型
引用数据类型
- 类 (class)
- 接口 (interface)
- 数组 (array)
运算符
- 算术运算符
- 加法运算符: +
- 减法运算符: -
- 乘法运算符: *
- 除法运算符: /
- 取余运算符: %
- 自增运算符: ++
- 自减运算符: --
public class ArithmeticOperator {
public static void main(String[] args) {
int a = 10;
int b = 3;
System.out.println(a + b); // 13
System.out.println(a - b); // 7
System.out.println(a * b); // 30
System.out.println(a / b); // 3
System.out.println(a % b); // 1
System.out.println(a++); // 10
System.out.println(++a); // 12
System.out.println(a--); // 12
System.out.println(--a); // 10
}
}
- 赋值运算符
- 基本赋值运算符: =
- 加法赋值运算符: +=
- 减法赋值运算符: -=
- 乘法赋值运算符: *=
- 除法赋值运算符: /=
- 取余赋值运算符: %=
public class AssignmentOperator {
public static void main(String[] args) {
int a = 10;
int b = 3;
a += b; // a = a + b;
System.out.println(a); // 13
a -= b; // a = a - b;
System.out.println(a); // 10
a *= b; // a = a * b;
System.out.println(a); // 30
a /= b; // a = a / b;
System.out.println(a); // 10
a %= b; // a = a % b;
System.out.println(a); // 1
}
}
- 比较运算符
- 大于运算符: >
- 小于运算符: <
- 大于等于运算符: >=
- 小于等于运算符: <=
- 等于运算符: ==
- 不等于运算符: !=
public class ComparisonOperator {
public static void main(String[] args) {
int a = 10;
int b = 3;
System.out.println(a > b); // true
System.out.println(a < b); // false
System.out.println(a >= b); // true
System.out.println(a <= b); // false
System.out.println(a == b); // false
System.out.println(a != b); // true
}
}
- 逻辑运算符
- 与运算符: &&
- 或运算符: ||
- 非运算符: !
public class LogicalOperator {
public static void main(String[] args) {
int a = 10;
int b = 3;
System.out.println(a > b && a < b); // false
System.out.println(a > b || a < b); // true
System.out.println(!(a > b)); // false
}
}
- 三元运算符
- 语法: 条件表达式 ? 表达式 1 : 表达式 2
- 执行流程: 如果条件表达式的值为 true, 则执行表达式 1, 否则执行表达式 2
public class TernaryOperator {
public static void main(String[] args) {
int a = 10;
int b = 3;
int max = a > b ? a : b;
System.out.println(max); // 10
}
}
- 位运算符
- 与运算符: &
- 或运算符: |
- 异或运算符: ^
- 取反运算符: ~
- 左移运算符: <<
- 右移运算符: >>
- 无符号右移运算符: >>>
public class BitwiseOperator {
public static void main(String[] args) {
int a = 10; // 1010
int b = 3; // 0011
System.out.println(a & b); // 0010
System.out.println(a | b); // 1011
System.out.println(a ^ b); // 1001
System.out.println(~a); // 11111111111111111111111111110101
System.out.println(a << 1); // 10100
System.out.println(a >> 1); // 101
System.out.println(a >>> 1); // 101
}
}
流程控制
- 顺序结构
- 分支结构
- 单分支结构
public class SingleBranchStructure { public static void main(String[] args) { int a = 10; int b = 3; if (a > b) { System.out.println("a > b"); } } }
- 双分支结构
public class DoubleBranchStructure { public static void main(String[] args) { int a = 10; int b = 3; if (a > b) { System.out.println("a > b"); } else { System.out.println("a <= b"); } } }
- 多分支结构
public class MultipleBranchStructure { public static void main(String[] args) { int a = 10; int b = 3; if (a > b) { System.out.println("a > b"); } else if (a < b) { System.out.println("a < b"); } else { System.out.println("a = b"); } } }
- 嵌套分支结构
public class NestedBranchStructure { public static void main(String[] args) { int a = 10; int b = 3; if (a > b) { if (a > 0) { System.out.println("a > b"); } else { System.out.println("a <= b"); } } else { System.out.println("a <= b"); } } }
- 单分支结构
- 循环结构
- while 循环
public class WhileLoop { public static void main(String[] args) { int i = 0; while (i < 10) { System.out.println(i); i++; } } }
- do while 循环
public class DoWhileLoop { public static void main(String[] args) { int i = 0; do { System.out.println(i); i++; } while (i < 10); } }
- for 循环
public class ForLoop { public static void main(String[] args) { for (int i = 0; i < 10; i++) { System.out.println(i); } } }
- 嵌套循环
public class NestedLoop { public static void main(String[] args) { for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { System.out.println(i + " " + j); } } } }
- while 循环
数组
数组: 存储同一种数据类型的多个元素的容器。
一维数组
- 定义格式: 数据类型[] 数组名 = new 数据类型[数组长度];
- 初始化格式: 数据类型[] 数组名 = new 数据类型[]{元素 1, 元素 2, 元素 3, ...};
- 简化格式: 数据类型[] 数组名 = {元素 1, 元素 2, 元素 3, ...};
public class OneDimensionalArray { public static void main(String[] args) { // 定义格式 int[] arr1 = new int[3]; // 初始化格式 int[] arr2 = new int[]{1, 2, 3}; // 简化格式 int[] arr3 = {1, 2, 3}; } }
二维数组
- 定义格式:
数据类型[][] 数组名 = new 数据类型[行长度][列长度]
; - 初始化格式:
数据类型[][] 数组名 = new 数据类型[][]{{元素 1, 元素 2, 元素 3, ...}, {元素 1, 元素 2, 元素 3, ...}, {元素 1, 元素 2, 元素 3, ...}}
; - 简化格式:
数据类型[][] 数组名 = {{元素 1, 元素 2, 元素 3, ...}, {元素 1, 元素 2, 元素 3, ...}, {元素 1, 元素 2, 元素 3, ...}}
;
public class TwoDimensionalArray { public static void main(String[] args) { // 定义格式 int[][] arr1 = new int[3][3]; // 初始化格式 int[][] arr2 = new int[][]{{1, 2, 3}, {1, 2, 3}, {1, 2, 3}}; // 简化格式 int[][] arr3 = {{1, 2, 3}, {1, 2, 3}, {1, 2, 3}}; } }
java 方法
- 无参无返回值方法
public class NoParameterNoReturnValueMethod { public static void main(String[] args) { printHelloWorld(); } public static void printHelloWorld() { System.out.println("Hello World!"); } }
- 无参有返回值方法
public class NoParameterReturnValueMethod { public static void main(String[] args) { System.out.println(getHelloWorld()); } public static String getHelloWorld() { return "Hello World!"; } }
- 有参无返回值方法
public class ParameterNoReturnValueMethod { public static void main(String[] args) { printHelloWorld("Hello World!"); } public static void printHelloWorld(String str) { System.out.println(str); } }
- 有参有返回值方法
public class ParameterReturnValueMethod { public static void main(String[] args) { System.out.println(getHelloWorld("Hello World!")); } public static String getHelloWorld(String str) { return str; } }
- 方法重载: 在同一个类中,方法名相同,参数列表不同的方法,互相构成重载。
public class MethodOverload { public static void main(String[] args) { System.out.println(sum(1, 2)); System.out.println(sum(1, 2, 3)); System.out.println(sum(1, 2, 3, 4)); } public static int sum(int a, int b) { return a + b; } public static int sum(int a, int b, int c) { return a + b + c; } public static int sum(int a, int b, int c, int d) { return a + b + c + d; } }
- 定义格式:
java 面向对象
对象与构造方法
- 对象: 万物皆对象,对象是内存中专门用来存储数据的一块区域。
- 构造方法: 用来创建对象的方法,构造方法的名称必须与类名相同,构造方法没有返回值类型,也不需要使用 void 关键字来修饰。
public class ConstructorMethod {
public static void main(String[] args) {
// 创建对象, 调用构造方法
// Person person = new Person();
Person person = new Person("张三", 18, true);
System.out.println(person.name);
System.out.println(person.age);
System.out.println(person.isMale);
}
}
class Person {
String name;
int age;
boolean isMale;
// public Person() {
// name = "张三";
// age = 18;
// isMale = true;
// }
// 或者 带参数构造方法
public Person (String name, int age, boolean isMale) {
this.name = name;
this.age = age;
this.isMale = isMale;
}
}
封装
- 封装: 隐藏对象的属性和实现细节,仅对外提供公共访问方式。
public class Encapsulation {
public static void main(String[] args) {
Person person = new Person();
person.setName("张三");
person.setAge(18);
person.setMale(true);
System.out.println(person.getName());
System.out.println(person.getAge());
System.out.println(person.isMale());
}
}
class Person {
private String name;
private int age;
private boolean isMale;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setMale(boolean isMale) {
this.isMale = isMale;
}
public boolean isMale() {
return isMale;
}
}
static 关键字
- static 关键字: 用来修饰成员变量和成员方法,被修饰的成员变量和成员方法属于类,而不属于对象,可以通过类名直接调用。
public class StaticKeyword {
public static void main(String[] args) {
Person person1 = new Person();
Person person2 = new Person();
Person person3 = new Person();
System.out.println(Person.count);
}
}
class Person {
String name;
int age;
boolean isMale;
static int count;
public Person() {
count++;
}
}
继承
- 继承: 子类继承父类,子类可以直接访问父类中的非私有成员变量和成员方法。
public class Inheritance {
public static void main(String[] args) {
Student student = new Student();
student.setName("张三");
student.setAge(18);
student.setMale(true);
student.setScore(100);
System.out.println(student.getName());
System.out.println(student.getAge());
System.out.println(student.isMale());
System.out.println(student.getScore());
}
}
class Person {
private String name;
private int age;
private boolean isMale;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setMale(boolean isMale) {
this.isMale = isMale;
}
public boolean isMale() {
return isMale;
}
}
// 继承 Person 类
class Student extends Person {
private int score;
public void setScore(int score) {
this.score = score;
}
public int getScore() {
return score;
}
}
Object 类
- Object 类: 所有类的父类,如果一个类没有使用 extends 关键字来继承其他类,那么默认继承 Object 类。
toString()
方法: 返回对象的字符串表示形式。equals()
方法: 比较两个对象是否相等。hashCode()
方法: 返回对象的哈希码值。getClass()
方法: 返回对象的运行时类。finalize()
方法: 当垃圾回收器确定不存在对该对象的更多引用时,由对象的垃圾回收器调用此方法。clone()
方法: 创建并返回此对象的一个副本。wait()
方法: 导致当前线程等待,直到另一个线程调用该对象的notify()
方法或notifyAll()
方法。notify()
方法: 唤醒正在等待对象监视器的单个线程。notifyAll()
方法: 唤醒正在等待对象监视器的所有线程。
public class ObjectClass {
public static void main(String[] args) {
Person person = new Person();
// toString 方法 继承自 Object 类
System.out.println(person.toString());
}
}
class Person {
private String name;
private int age;
private boolean isMale;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setMale(boolean isMale) {
this.isMale = isMale;
}
public boolean isMale() {
return isMale;
}
}
final 关键字
- final 关键字: 用来修饰类、成员变量和成员方法,被修饰的类不能被继承,被修饰的成员变量不能被修改,被修饰的成员方法不能被重写。
public class FinalKeyword {
public static void main(String[] args) {
Person person = new Person();
// final 修饰的成员变量不能被修改
// person.name = "张三";
person.setAge(18);
person.setMale(true);
System.out.println(person.getName());
System.out.println(person.getAge());
System.out.println(person.isMale());
}
}
// final 修饰的类不能被继承
final class Person {
private final String name = "张三";
private int age;
private boolean isMale;
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setMale(boolean isMale) {
this.isMale = isMale;
}
public boolean isMale() {
return isMale;
}
}
java 单例模式
- 单例模式: 保证一个类仅有一个实例,并提供一个访问它的全局访问点。
public class SingletonPattern {
public static void main(String[] args) {
// 创建对象
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
// 判断是否为同一个对象
System.out.println(singleton1 == singleton2);
}
}
class Singleton {
// 私有化构造方法
private Singleton() {}
// 创建对象
private static Singleton singleton = new Singleton();
// 提供访问对象的全局访问点
public static Singleton getInstance() {
return singleton;
}
}
抽象类
- 抽象类: 用来修饰类,被修饰的类称为抽象类,抽象类不能被实例化,抽象类中可以包含抽象方法和非抽象方法,抽象类的子类必须实现抽象类中的所有抽象方法。
public class AbstractClass {
public static void main(String[] args) {
// 抽象类不能被实例化
// Person person = new Person();
Student student = new Student();
student.setName("张三");
student.setAge(18);
student.setMale(true);
student.setScore(100);
System.out.println(student.getName());
System.out.println(student.getAge());
System.out.println(student.isMale());
System.out.println(student.getScore());
}
}
// 抽象类
abstract class Person {
private String name;
private int age;
private boolean isMale;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setMale(boolean isMale) {
this.isMale = isMale;
}
public boolean isMale() {
return isMale;
}
// 抽象方法
public abstract void setScore(int score);
public abstract int getScore();
}
// 抽象类的子类必须实现抽象类中的所有抽象方法
class Student extends Person {
private int score;
public void setScore(int score) {
this.score = score;
}
public int getScore() {
return score;
}
}
接口
- 接口: 用来修饰类,被修饰的类称为接口,接口中可以包含抽象方法和默认方法,接口的子类必须实现接口中的所有抽象方法。
public class Interface {
public static void main(String[] args) {
// 接口不能被实例化
// Person person = new Person();
Student student = new Student();
student.setName("张三");
student.setAge(18);
student.setMale(true);
student.setScore(100);
System.out.println(student.getName());
System.out.println(student.getAge());
System.out.println(student.isMale());
System.out.println(student.getScore());
}
}
// 接口
interface Person {
void setName(String name);
String getName();
void setAge(int age);
int getAge();
void setMale(boolean isMale);
boolean isMale();
}
// 接口的子类必须实现接口中的所有抽象方法
class Student implements Person {
private int score;
public void setScore(int score) {
this.score = score;
}
public int getScore() {
return score;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setMale(boolean isMale) {
this.isMale = isMale;
}
public boolean isMale() {
return isMale;
}
}
多态
- 多态: 同一个行为具有多个不同表现形式或形态的能力。
public class Polymorphism {
public static void main(String[] args) {
// 多态: 父类的引用指向子类的对象
Person person = new Student();
person.setName("张三");
person.setAge(18);
person.setMale(true);
// person.setScore(100);
System.out.println(person.getName());
System.out.println(person.getAge());
System.out.println(person.isMale());
// System.out.println(person.getScore());
}
}
// 抽象类
abstract class Person {
private String name;
private int age;
private boolean isMale;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setMale(boolean isMale) {
this.isMale = isMale;
}
public boolean isMale() {
return isMale;
}
// 抽象方法
public abstract void setScore(int score);
public abstract int getScore();
}
// 抽象类的子类必须实现抽象类中的所有抽象方法
class Student extends Person {
private int score;
public void setScore(int score) {
this.score = score;
}
public int getScore() {
return score;
}
}
内部类
- 内部类: 在一个类的内部定义的类,被定义的类称为内部类,内部类可以直接访问外部类的成员变量和成员方法,内部类的成员变量和成员方法不能被 static 修饰。
public class InnerClass {
public static void main(String[] args) {
// 创建内部类对象
Outer.Inner inner = new Outer().new Inner();
inner.printHelloWorld();
}
}
// 外部类
class Outer {
private String name = "张三";
// 内部类
class Inner {
public void printHelloWorld() {
// 内部类可以直接访问外部类的成员变量和成员方法
System.out.println(name);
}
}
}
- 匿名内部类: 在一个类的内部定义的类,被定义的类称为内部类,内部类可以直接访问外部类的成员变量和成员方法,内部类的成员变量和成员方法不能被 static 修饰。
public class AnonymousInnerClass {
public static void main(String[] args) {
// 创建内部类对象
Outer outer = new Outer();
outer.printHelloWorld();
}
}
// 外部类
class Outer {
private String name = "张三";
public void printHelloWorld() {
// 匿名内部类
new Inner() {
public void printHelloWorld() {
// 内部类可以直接访问外部类的成员变量和成员方法
System.out.println(name);
}
}.printHelloWorld();
}
}
java 常用工具类
java 异常
- 异常: 在程序运行过程中,出现的不正常情况,例如: 空指针异常、数组下标越界异常、类型转换异常、算术异常等。
- 异常处理: 在程序运行过程中,出现异常时,程序会终止运行,为了保证程序的正常运行,需要对异常进行处理。
public class Exception {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
try {
System.out.println(arr[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组下标越界异常");
}
}
}
try...catch...finally 异常处理
public class TryCatchFinally { public static void main(String[] args) { int[] arr = {1, 2, 3}; try { System.out.println(arr[3]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("数组下标越界异常"); } finally { System.out.println("finally"); } } }
使用 throw he throws 关键字抛出异常
public class ThrowAndThrows { public static void main(String[] args) { int[] arr = {1, 2, 3}; try { System.out.println(getElement(arr, 3)); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("数组下标越界异常"); } } public static int getElement(int[] arr, int index) throws ArrayIndexOutOfBoundsException { if (index < 0 || index > arr.length - 1) { throw new ArrayIndexOutOfBoundsException("数组下标越界异常"); } return arr[index]; } }
自定义异常
public class CustomException { public static void main(String[] args) { int[] arr = {1, 2, 3}; try { System.out.println(getElement(arr, 3)); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(e.getMessage()); } } public static int getElement(int[] arr, int index) throws ArrayIndexOutOfBoundsException { if (index < 0 || index > arr.length - 1) { throw new ArrayIndexOutOfBoundsException("数组下标越界异常"); } return arr[index]; } }
java 包装类
包装类: 为了方便操作基本数据类型,java 为每一种基本数据类型都提供了对应的包装类,包装类位于 java.lang 包中,包装类和基本数据类型的对应关系如下:
基本数据类型 包装类 byte Byte short Short int Integer long Long float Float double Double char Character boolean Boolean 包装类的常用方法
public static int parseInt(String s)
: 将字符串参数转换为对应的基本数据类型 int。public static String toString(int i)
: 将基本数据类型 int 转换为对应的字符串。public static Integer valueOf(int i)
: 将基本数据类型 int 转换为对应的包装类 Integer。public static Integer valueOf(String s)
: 将字符串参数转换为对应的包装类 Integer。public static Integer valueOf(String s, int radix)
: 将字符串参数按照指定的进制转换为对应的包装类 Integer。public static int valueOf(String s).intValue()
: 将字符串参数转换为对应的基本数据类型 int。public static String toBinaryString(int i)
: 将基本数据类型 int 转换为对应的二进制字符串。public static String toOctalString(int i)
: 将基本数据类型 int 转换为对应的八进制字符串。public static String toHexString(int i)
: 将基本数据类型 int 转换为对应的十六进制字符串。
public class WrapperClass { public static void main(String[] args) { // 将字符串参数转换为对应的基本数据类型 int System.out.println(Integer.parseInt("1")); // 将基本数据类型 int 转换为对应的字符串 System.out.println(Integer.toString(1)); // 将基本数据类型 int 转换为对应的包装类 Integer System.out.println(Integer.valueOf(1)); // 将字符串参数转换为对应的包装类 Integer System.out.println(Integer.valueOf("1")); // 将字符串参数按照指定的进制转换为对应的包装类 Integer System.out.println(Integer.valueOf("1", 2)); // 将字符串参数转换为对应的基本数据类型 int System.out.println(Integer.valueOf("1").intValue()); // 将基本数据类型 int 转换为对应的二进制字符串 System.out.println(Integer.toBinaryString(1)); // 将基本数据类型 int 转换为对应的八进制字符串 System.out.println(Integer.toOctalString(1)); // 将基本数据类型 int 转换为对应的十六进制字符串 System.out.println(Integer.toHexString(1)); } }
字符串
字符串: 字符串是一种引用数据类型,字符串的值是一个常量,字符串的值不能被修改,字符串的值在内存中存储在字符串常量池中。
字符串的定义
- 直接赋值:
String str = "Hello World!";
- 构造方法:
String str = new String("Hello World!");
- 直接赋值:
字符串的常用方法
public int length()
: 返回字符串的长度。public char charAt(int index)
: 返回字符串中指定索引处的字符。public int indexOf(String str)
: 返回字符串中指定字符串第一次出现的索引。public int indexOf(String str, int fromIndex)
: 返回字符串中指定字符串从指定索引处开始第一次出现的索引。public String substring(int beginIndex)
: 返回字符串中从指定索引处开始到末尾的子字符串。public String substring(int beginIndex, int endIndex)
: 返回字符串中从指定索引处开始到指定索引处结束的子字符串。public String replace(char oldChar, char newChar)
: 返回字符串中指定字符替换为新字符后的字符串。public String replace(CharSequence target, CharSequence replacement)
: 返回字符串中指定字符串替换为新字符串后的字符串。public String[] split(String regex)
: 返回字符串根据指定正则表达式拆分后的字符串数组。public String[] split(String regex, int limit)
: 返回字符串根据指定正则表达式拆分后的字符串数组,最多拆分 limit - 1 次。public String trim()
: 返回字符串去除首尾空格后的字符串。public String toLowerCase()
: 返回字符串转换为小写后的字符串。public String toUpperCase()
: 返回字符串转换为大写后的字符串。public boolean equals(Object obj)
: 判断字符串是否相等。public boolean equalsIgnoreCase(String anotherString)
: 判断字符串是否相等,忽略大小写。public boolean contains(CharSequence s)
: 判断字符串是否包含指定字符串。public boolean startsWith(String prefix)
: 判断字符串是否以指定字符串开头。public boolean endsWith(String suffix)
: 判断字符串是否以指定字符串结尾。
public class StringClass { public static void main(String[] args) { String str = "Hello World!"; // 返回字符串的长度 System.out.println(str.length()); // 返回字符串中指定索引处的字符 System.out.println(str.charAt(0)); // 返回字符串中指定字符串第一次出现的索引 System.out.println(str.indexOf("l")); // 返回字符串中指定字符串从指定索引处开始第一次出现的索引 System.out.println(str.indexOf("l", 3)); // 返回字符串中从指定索引处开始到末尾的子字符串 System.out.println(str.substring(3)); // 返回字符串中从指定索引处开始到指定索引处结束的子字符串 System.out.println(str.substring(3, 7)); // 返回字符串中指定字符替换为新字符后的字符串 System.out.println(str.replace("l", "L")); // 返回字符串中指定字符串替换为新字符串后的字符串 System.out.println(str.replace("l", "L")); // 返回字符串根据指定正则表达式拆分后的字符串数组 System.out.println(Arrays.toString(str.split(" "))); // 返回字符串根据指定正则表达式拆分后的字符串数组,最多拆分 limit - 1 次 System.out.println(Arrays.toString(str.split(" ", 1))); // 返回字符串去除首尾空格后的字符串 System.out.println(str.trim()); // 返回字符串转换为小写后的字符串 System.out.println(str.toLowerCase()); // 返回字符串转换为大写后的字符串 System.out.println(str.toUpperCase()); // 判断字符串是否相等 System.out.println(str.equals("Hello World!")); // 判断字符串是否相等,忽略大小写 System.out.println(str.equalsIgnoreCase("hello world!")); // 判断字符串是否包含指定字符串 System.out.println(str.contains("l")); // 判断字符串是否以指定字符串开头 System.out.println(str.startsWith("H")); // 判断字符串是否以指定字符串结尾 System.out.println(str.endsWith("!")); } }
StringBuffer 类
StringBuffer 类: 字符串缓冲区类,用来存储数据,字符串缓冲区类的对象是可变的,字符串缓冲区类的对象在内存中存储在堆内存中。
字符串缓冲区类的常用方法
public StringBuffer append(String str)
: 将指定字符串追加到字符串缓冲区类的对象中。public StringBuffer insert(int offset, String str)
: 将指定字符串插入到字符串缓冲区类的对象中的指定位置。public StringBuffer delete(int start, int end)
: 删除字符串缓冲区类的对象中从指定索引处开始到指定索引处结束的字符串。public StringBuffer replace(int start, int end, String str)
: 将字符串缓冲区类的对象中从指定索引处开始到指定索引处结束的字符串替换为指定字符串。public StringBuffer reverse()
: 将字符串缓冲区类的对象中的字符串反转。public String substring(int start)
: 返回字符串缓冲区类的对象中从指定索引处开始到末尾的子字符串。public String substring(int start, int end)
: 返回字符串缓冲区类的对象中从指定索引处开始到指定索引处结束的子字符串。public int indexOf(String str)
: 返回字符串缓冲区类的对象中指定字符串第一次出现的索引。public int indexOf(String str, int fromIndex)
: 返回字符串缓冲区类的对象中指定字符串从指定索引处开始第一次出现的索引。public int lastIndexOf(String str)
: 返回字符串缓冲区类的对象中指定字符串最后一次出现的索引。public int lastIndexOf(String str, int fromIndex)
: 返回字符串缓冲区类的对象中指定字符串从指定索引处开始最后一次出现的索引。public int length()
: 返回字符串缓冲区类的对象中字符串的长度。public void setLength(int newLength)
: 设置字符串缓冲区类的对象中字符串的长度。
public class StringBufferClass { public static void main(String[] args) { StringBuffer stringBuffer = new StringBuffer(); // 将指定字符串追加到字符串缓冲区类的对象中 stringBuffer.append("Hello World!"); // 将指定字符串插入到字符串缓冲区类的对象中的指定位置 stringBuffer.insert(0, "Hello "); // 删除字符串缓冲区类的对象中从指定索引处开始到指定索引处结束的字符串 stringBuffer.delete(0, 6); // 将字符串缓冲区类的对象中从指定索引处开始到指定索引处结束的字符串替换为指定字符串 stringBuffer.replace(0, 5, "Hello"); // 将字符串缓冲区类的对象中的字符串反转 stringBuffer.reverse(); // 返回字符串缓冲区类的对象中从指定索引处开始到末尾的子字符串 stringBuffer.substring(0); // 返回字符串缓冲区类的对象中从指定索引处开始到指定索引处结束的子字符串 stringBuffer.substring(0, 5); // 返回字符串缓冲区类的对象中指定字符串第一次出现的索引 stringBuffer.indexOf("l"); // 返回字符串缓冲区类的对象中指定字符串从指定索引处开始第一次出现的索引 stringBuffer.indexOf("l", 3); // 返回字符串缓冲区类的对象中指定字符串最后一次出现的索引 stringBuffer.lastIndexOf("l"); // 返回字符串缓冲区类的对象中指定字符串从指定索引处开始最后一次出现的索引 stringBuffer.lastIndexOf("l", 3); // 返回字符串缓冲区类的对象中字符串的长度 stringBuffer.length(); // 设置字符串缓冲区类的对象中字符串的长度 stringBuffer.setLength(5); } }
集合
集合: 用来存储数据的容器,集合中的数据类型可以是基本数据类型,也可以是引用数据类型,集合中的数据个数可以是固定的,也可以是可变的,集合中的数据是无序的,集合中的数据是可重复的。
集合的分类
- Collection: 集合的根接口,用来存储单个对象的集合。
- List: 有序集合,存储的数据是有序的,存储的数据是可重复的。
- ArrayList: 底层是数组,查询快,增删慢。
- LinkedList: 底层是链表,查询慢,增删快。
- Vector: 底层是数组,线程安全,效率低。
- Set: 无序集合,存储的数据是无序的,存储的数据是不可重复的。
- HashSet: 底层是哈希表,存储的数据是无序的,存储的数据是不可重复的。
- LinkedHashSet: 底层是哈希表和链表,存储的数据是有序的,存储的数据是不可重复的。
- TreeSet: 底层是红黑树,存储的数据是有序的,存储的数据是不可重复的。
- List: 有序集合,存储的数据是有序的,存储的数据是可重复的。
- Map: 用来存储键值对的集合。
- HashMap: 底层是哈希表,存储的数据是无序的,存储的键是不可重复的,存储的值是可重复的。
- LinkedHashMap: 底层是哈希表和链表,存储的数据是有序的,存储的键是不可重复的,存储的值是可重复的。
- TreeMap: 底层是红黑树,存储的数据是有序的,存储的键是不可重复。
- Collection: 集合的根接口,用来存储单个对象的集合。
List
List: 有序集合,存储的数据是有序的,存储的数据是可重复的。
List 的常用方法
public boolean add(E e)
: 将指定元素添加到列表的尾部。public void add(int index, E element)
: 将指定元素插入到列表的指定位置。public E get(int index)
: 返回列表中指定位置的元素。public E set(int index, E element)
: 用指定元素替换列表中指定位置的元素。public E remove(int index)
: 移除列表中指定位置的元素。public int indexOf(Object o)
: 返回列表中指定元素第一次出现的索引。public int lastIndexOf(Object o)
: 返回列表中指定元素最后一次出现的索引。public int size()
: 返回列表中的元素个数。public boolean isEmpty()
: 判断列表是否为空。public void clear()
: 清空列表中的所有元素。public boolean contains(Object o)
: 判断列表是否包含指定元素。public boolean containsAll(Collection<?> c)
: 判断列表是否包含指定集合中的所有元素。public Object[] toArray()
: 返回包含列表中所有元素的数组。public <T> T[] toArray(T[] a)
: 返回包含列表中所有元素的数组。
public class ListClass { public static void main(String[] args) { List<String> list = new ArrayList<>(); // 将指定元素添加到列表的尾部 list.add("Hello"); // 将指定元素插入到列表的指定位置 list.add(0, "Hello"); // 返回列表中指定位置的元素 list.get(0); // 用指定元素替换列表中指定位置的元素 list.set(0, "Hello"); // 移除列表中指定位置的元素 list.remove(0); // 返回列表中指定元素第一次出现的索引 list.indexOf("Hello"); // 返回列表中指定元素最后一次出现的索引 list.lastIndexOf("Hello"); // 返回列表中的元素个数 list.size(); // 判断列表是否为空 list.isEmpty(); // 清空列表中的所有元素 list.clear(); // 判断列表是否包含指定元素 list.contains("Hello"); // 判断列表是否包含指定集合中的所有元素 list.containsAll(list); // 返回包含列表中所有元素的数组 list.toArray(); // 返回包含列表中所有元素的数组 list.toArray(new String[0]); } }
Set
Set: 无序集合,存储的数据是无序的,存储的数据是不可重复的。
Set 的常用方法
public boolean add(E e)
: 将指定元素添加到集合中。public boolean remove(Object o)
: 移除集合中指定元素。public int size()
: 返回集合中的元素个数。public boolean isEmpty()
: 判断集合是否为空。public void clear()
: 清空集合中的所有元素。public boolean contains(Object o)
: 判断集合是否包含指定元素。public boolean containsAll(Collection<?> c)
: 判断集合是否包含指定集合中的所有元素。public Object[] toArray()
: 返回包含集合中所有元素的数组。public <T> T[] toArray(T[] a)
: 返回包含集合中所有元素的数组。
public class SetClass { public static void main(String[] args) { Set<String> set = new HashSet<>(); // 将指定元素添加到集合中 set.add("Hello"); // 移除集合中指定元素 set.remove("Hello"); // 返回集合中的元素个数 set.size(); // 判断集合是否为空 set.isEmpty(); // 清空集合中的所有元素 set.clear(); // 判断集合是否包含指定元素 set.contains("Hello"); // 判断集合是否包含指定集合中的所有元素 set.containsAll(set); // 返回包含集合中所有元素的数组 set.toArray(); // 返回包含集合中所有元素的数组 set.toArray(new String[0]); } }
Map
Map: 用来存储键值对的集合。
Map 的常用方法
public V put(K key, V value)
: 将指定的键值对添加到映射中。public V remove(Object key)
: 移除映射中指定键所对应的键值对。public V get(Object key)
: 返回映射中指定键所对应的值。public boolean containsKey(Object key)
: 判断映射中是否包含指定的键。public boolean containsValue(Object value)
: 判断映射中是否包含指定的值。public int size()
: 返回映射中键值对的个数。public boolean isEmpty()
: 判断映射是否为空。public void clear()
: 清空映射中的所有键值对。public Set<K> keySet()
: 返回映射中所有键的集合。public Collection<V> values()
: 返回映射中所有值的集合。public Set<Map.Entry<K, V>> entrySet()
: 返回映射中所有键值对的集合。
public class MapClass { public static void main(String[] args) { Map<String, String> map = new HashMap<>(); // 将指定的键值对添加到映射中 map.put("Hello", "World"); // 移除映射中指定键所对应的键值对 map.remove("Hello"); // 返回映射中指定键所对应的值 map.get("Hello"); // 判断映射中是否包含指定的键 map.containsKey("Hello"); // 判断映射中是否包含指定的值 map.containsValue("World"); // 返回映射中键值对的个数 map.size(); // 判断映射是否为空 map.isEmpty(); // 清空映射中的所有键值对 map.clear(); // 返回映射中所有键的集合 map.keySet(); // 返回映射中所有值的集合 map.values(); // 返回映射中所有键值对的集合 map.entrySet(); } }
泛型
泛型: 泛型是一种数据类型,泛型可以用来指定集合中存储的数据类型,泛型只能是引用数据类型,泛型只能是类或接口,泛型不能是基本数据类型。
泛型的定义
- 泛型类:
public class GenericClass<T> {}
- 泛型接口:
public interface GenericInterface<T> {}
- 泛型方法:
public <T> void genericMethod(T t) {}
- 泛型类:
泛型的使用
public class Generic { public static void main(String[] args) { // 泛型类 GenericClass<String> genericClass = new GenericClass<>(); genericClass.setT("Hello"); System.out.println(genericClass.getT()); // 泛型接口 GenericInterface<String> genericInterface = new GenericInterface<String>() { @Override public void genericMethod(String s) { System.out.println(s); } }; genericInterface.genericMethod("Hello"); // 泛型方法 genericMethod("Hello"); } public static <T> void genericMethod(T t) { System.out.println(t); } } // 泛型类 class GenericClass<T> { private T t; public void setT(T t) { this.t = t; } public T getT() { return t; } } // 泛型接口 interface GenericInterface<T> { public void genericMethod(T t); }
迭代器
迭代器: 用来遍历集合中的元素,迭代器是一个接口,迭代器的实现类位于 java.util 包中,迭代器的实现类是集合的内部类,迭代器的实现类不能直接创建对象,迭代器的实现类的对象是通过集合的 iterator() 方法创建的。
迭代器的常用方法
public boolean hasNext()
: 判断迭代器中是否还有下一个元素。public E next()
: 返回迭代器中的下一个元素。public void remove()
: 移除迭代器中的元素。
public class IteratorClass { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("Hello"); list.add("World"); Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } }
多线程
多线程: 在一个进程中同时执行多个任务,每个任务称为一个线程,多个线程共享进程的资源,多个线程之间可以并发执行,多个线程之间也可以同步执行。
多线程的实现方式
- 继承 Thread 类:
public class ThreadClass extends Thread {}
- 实现 Runnable 接口:
public class RunnableClass implements Runnable {}
- 继承 Thread 类:
多线程的常用方法
public void start()
: 启动线程。public void run()
: 线程执行的任务。public static void sleep(long millis)
: 使当前正在执行的线程休眠指定的毫秒数。public final void join()
: 等待该线程终止。public final void setPriority(int newPriority)
: 更改线程的优先级。public final void setName(String name)
: 更改线程的名称。public final String getName()
: 返回线程的名称。public final ThreadGroup getThreadGroup()
: 返回线程所属的线程组。public static Thread currentThread()
: 返回当前正在执行的线程。public final boolean isAlive()
: 判断线程是否处于活动状态。public final void wait()
: 导致当前线程等待,直到另一个线程调用该对象的 notify() 方法或 notifyAll() 方法。public final void notify()
: 唤醒在此对象监视器上等待的单个线程。public final void notifyAll()
: 唤醒在此对象监视器上等待的所有线程。
public class ThreadClass { public static void main(String[] args) { // 继承 Thread 类 Thread thread1 = new ThreadClass1(); thread1.start(); // 实现 Runnable 接口 Thread thread2 = new Thread(new ThreadClass2()); thread2.start(); } } // 继承 Thread 类 class ThreadClass1 extends Thread { @Override public void run() { System.out.println("Hello"); } } // 实现 Runnable 接口 class ThreadClass2 implements Runnable { @Override public void run() { System.out.println("World"); } }
输入输出流
输入输出流: 用来读取数据和写入数据的流,输入流用来读取数据,输出流用来写入数据,输入输出流位于 java.io 包中,输入输出流是抽象类,输入输出流的实现类位于 java.io 包中,输入输出流的实现类不能直接创建对象,输入输出流的实现类的对象是通过输入输出流的工具类创建的。
输入输出流的实现类
- 字节输入流:
public class InputStreamClass extends InputStream {}
- 字节输出流:
public class OutputStreamClass extends OutputStream {}
- 字符输入流:
public class ReaderClass extends Reader {}
- 字符输出流:
public class WriterClass extends Writer {}
- 字节输入流:
输入输出流的工具类
- 字节输入流工具类:
public class InputStreamUtil {}
- 字节输出流工具类:
public class OutputStreamUtil {}
- 字符输入流工具类:
public class ReaderUtil {}
- 字符输出流工具类:
public class WriterUtil {}
- 字节输入流工具类:
输入输出流的常用方法
public int read()
: 读取一个字节的数据。public int read(byte[] b)
: 读取多个字节的数据。public int read(byte[] b, int off, int len)
: 读取多个字节的数据。public void write(int b)
: 写入一个字节的数据。public void write(byte[] b)
: 写入多个字节的数据。public void write(byte[] b, int off, int len)
: 写入多个字节的数据。public void close()
: 关闭流。
public class InputStreamClass { public static void main(String[] args) throws IOException { // 字节输入流 InputStream inputStream = new FileInputStream("input.txt"); // 读取一个字节的数据 System.out.println(inputStream.read()); // 读取多个字节的数据 byte[] bytes1 = new byte[1024]; System.out.println(inputStream.read(bytes1)); // 读取多个字节的数据 byte[] bytes2 = new byte[1024]; System.out.println(inputStream.read(bytes2, 0, 1024)); // 关闭流 inputStream.close(); } } public class OutputStreamClass { public static void main(String[] args) throws IOException { // 字节输出流 OutputStream outputStream = new FileOutputStream("output.txt"); // 写入一个字节的数据 outputStream.write(97); // 写入多个字节的数据 byte[] bytes1 = {97, 98, 99}; outputStream.write(bytes1); // 写入多个字节的数据 byte[] bytes2 = {97, 98, 99}; outputStream.write(bytes2, 0, 3); // 关闭流 outputStream.close(); } } public class ReaderClass { public static void main(String[] args) throws IOException { // 字符输入流 Reader reader = new FileReader("input.txt"); // 读取一个字符的数据 System.out.println(reader.read()); // 读取多个字符的数据 char[] chars1 = new char[1024]; System.out.println(reader.read(chars1)); // 读取多个字符的数据 char[] chars2 = new char[1024]; System.out.println(reader.read(chars2, 0, 1024)); // 关闭流 reader.close(); } } public class WriterClass { public static void main(String[] args) throws IOException { // 字符输出流 Writer writer = new FileWriter("output.txt"); // 写入一个字符的数据 writer.write(97); // 写入多个字符的数据 char[] chars1 = {97, 98, 99}; writer.write(chars1); // 写入多个字符的数据 char[] chars2 = {97, 98, 99}; writer.write(chars2, 0, 3); // 关闭流 writer.close(); } }