Java基础合集
1 数据类型与输入输出
1.1 内置数据类型
| 类型 | 字节数 | 举例 |
|---|---|---|
| byte | 1 | 123 |
| short | 2 | 12345 |
| int | 4 | 123456789 |
| long | 8 | 1234567891011L |
| float | 4 | 1.2F |
| double | 8 | 1.2, 1.2D |
| boolean | 1 | true, false |
| char | 2 | 'A' |
1.2 常量
使用 final 修饰:
final int N = 110;
1.3 类型转换
-
显示转换:
int x = (int)'A'; -
隐式转换:
double x = 12, y = 4 * 3.3;
1.4 表达式
与 C++、Python3 类似:
int a = 1, b = 2, c = 3;
int x = (a + b) * c;
x++;
1.5 输入
-
方式1(效率较低,适用于小规模输入):
Scanner sc = new Scanner(System.in); String str = sc.next(); // 读入下一个字符串 int x = sc.nextInt(); // 读入下一个整数 float y = sc.nextFloat(); // 读入下一个单精度浮点数 double z = sc.nextDouble(); // 读入下一个双精度浮点数 String line = sc.nextLine(); // 读入下一行 -
方式2(效率较高,适用于大规模输入,注意需要抛异常):
package com.muqyy;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
System.out.println(str);
}
}
1.6 输出
-
方式1(效率较低,适用于小规模输出):
System.out.println(123); // 输出整数 + 换行 System.out.println("Hello World"); // 输出字符串 + 换行 System.out.print(123); // 输出整数 System.out.print("yxc\n"); // 输出字符串 System.out.printf("%04d %.2f\n", 4, 123.456D); // 格式化输出,float 与 double 都用 %f 输出 -
方式2(效率较高,适用于大规模输出,注意需要抛异常):
package com.muqyy;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
public class Main {
public static void main(String[] args) throws Exception {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
bw.write("Hello World\n");
bw.flush(); // 需要手动刷新缓冲区
}
}
2 判断语句
2.1 if-else语句
与C++、Python中类似。
例如:
package com.muqyy;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int year = sc.nextInt();
if (year % 100 == 0) {
if (year % 400 == 0)
System.out.printf("%d是闰年\n", year);
else
System.out.printf("%d不是闰年\n", year);
} else {
if (year % 4 == 0)
System.out.printf("%d是闰年\n", year);
else
System.out.printf("%d不是闰年\n", year);
}
}
}
2.2 switch语句
与C++中类似。
package com.muqyy;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int day = sc.nextInt();
String name;
switch (day) {
case 1:
name = "Monday";
break;
case 2:
name = "Tuesday";
break;
case 3:
name = "Wednesday";
break;
case 4:
name = "Thursday";
break;
case 5:
name = "Friday";
break;
case 6:
name = "Saturday";
break;
case 7:
name = "Sunday";
break;
default:
name = "not valid";
}
System.out.println(name);
}
}
2.3 逻辑运算符与条件表达式
与C++、Python类似。
例如:
package com.muqyy;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int year = sc.nextInt();
if (year % 100 != 0 && year % 4 == 0 || year % 400 == 0)
System.out.printf("%d是闰年\n", year);
else
System.out.printf("%d不是闰年\n", year);
}
}
3 循环语句
3.1 while循环
与C++、Python类似。
例如:
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
3.2 do-while循环
与C++、Python类似。
例如:
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
do-while 语句与 while 语句非常相似。唯一的区别是,do-while 语句在循环体后检查条件。不管条件的值如何,都会至少执行一次循环。
3.3 for循环
与C++、Python类似。
例如:
for (int i = 0; i < 5; i++) { // 普通循环
System.out.println(i);
}
int[] a = {0, 1, 2, 3, 4};
for (int x: a) { // forEach循环
System.out.println(x);
}
4 数组
4.1 初始化
与C++类似。
初始化定长数组,长度可以是变量,也可以在初始化时赋值。
int[] a = new int[5]; // 初始化长度为5的int数组,初始值为0
int n = 10;
float[] b = new float[n]; // 初始化长度为n的float数组,初始值为0.0F
char[] c = {'a', 'b', 'c'}; // 初始化长度为3的char数组,初始值为:'a', 'b', 'c'
char[] d = c; // d与c地址相同,更改c中的元素,d中的元素也会改变
4.2 数组元素的读取与写入
与C++类似。
int[] a = new int[5];
for (int i = 0; i < 5; i++) {
a[i] = i;
}
for (int i = 0; i < 5; i++) {
System.out.println(a[i] * a[i]);
}
4.3 多维数组
与C++类似。
int[][] a = new int[2][3];
a[1][2] = 1;
int[][] b = {
{1, 2, 3},
{4, 5, 6},
};
System.out.println(a[1][2]);
System.out.println(b[0][1]);
4.4 常用API
- 属性
length:返回数组长度,注意不加小括号 Arrays.sort():数组排序Arrays.fill(int[] a, int val):填充数组Arrays.toString():将数组转化为字符串Arrays.deepToString():将多维数组转化为字符串
注意:数组不可变长。
5 字符串
5.1 String类
初始化:
String a = "Hello World";
String b = "My name is";
String x = b; // 存储到了相同地址
String c = b + "MuQYY"; // String可以通过加号拼接
String d = "My age is " + 18; // int会被隐式转化成字符串"18"
String str = String.format("My age is %d", 18); // 格式化字符串,类似于C++中的sprintf
String money_str = "123.45";
double money = Double.parseDouble(money_str); // String转double
只读变量,不能修改,例如:
String a = "Hello ";
a += "World"; // 会构造一个新的字符串
访问String中的字符:
String str = "Hello World";
for (int i = 0; i < str.length(); i++) {
System.out.print(str.charAt(i)); // 只能读取,不能写入
}
常用API:
length():返回长度split(String regex):分割字符串indexOf(char c)、indexOf(String str):查找,找不到返回-1equals():判断两个字符串是否相等,注意不能直接用==compareTo():判断两个字符串的字典序大小,负数表示小于,0表示相等,正数表示大于startsWith():判断是否以某个前缀开头endsWith():判断是否以某个后缀结尾trim():去掉首尾的空白字符toLowerCase():全部用小写字符toUpperCase():全部用大写字符replace(char oldChar, char newChar):替换字符replace(String oldRegex, String newRegex):替换字符串substring(int beginIndex, int endIndex):返回[beginIndex, endIndex)中的子串
5.2 StringBuilder、StringBuffer
String 不能被修改,如果打算修改字符串,可以使用 StringBuilder 和 StringBuffer。
StringBuffer 线程安全,速度较慢;StringBuilder 线程不安全,速度较快。
StringBuilder sb = new StringBuilder("Hello "); // 初始化
sb.append("World"); // 拼接字符串
System.out.println(sb);
for (int i = 0; i < sb.length(); i++) {
sb.setCharAt(i, (char)(sb.charAt(i) + 1)); // 读取和写入字符
}
System.out.println(sb);
常用API:
reverse():翻转字符串
6 函数
Java 的所有变量和函数都要定义在类中。
函数或变量前加 static 表示静态对象,类似于全局变量。
静态对象属于类(class),而不属于类的具体实例。
- 静态函数中只能调用静态函数和静态变量。
示例代码:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
System.out.println(max(3, 4));
int[][] a = new int[3][4];
fill(a, 3);
System.out.println(Arrays.deepToString(a));
int[][] b = getArray2d(2, 3, 5);
System.out.println(Arrays.deepToString(b));
}
// 静态函数 max
private static int max(int a, int b) {
if (a > b) return a;
return b;
}
// 静态函数 fill,用于填充二维数组
private static void fill(int[][] a, int val) {
for (int i = 0; i < a.length; i++)
for (int j = 0; j < a[i].length; j++)
a[i][j] = val;
}
// 静态函数 getArray2d,用于生成并填充二维数组
private static int[][] getArray2d(int row, int col, int val) {
int[][] a = new int[row][col];
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
a[i][j] = val;
return a;
}
}
说明:
max(int a, int b):静态方法,用于返回两个数中的最大值。fill(int[][] a, int val):静态方法,用于填充一个二维数组的所有元素为val。getArray2d(int row, int col, int val):静态方法,生成一个给定行和列的二维数组,并将所有元素填充为val。
7 类与接口
7.1 类
class 与 C++、Python 类似。
7.1.1 源文件声明规则
- 一个源文件中只能有一个
public类。 - 一个源文件可以有多个非
public类。 - 源文件的名称应该和
public类的类名保持一致。 - 每个源文件中,先写
package语句,再写import语句,最后定义类。
7.1.2 类的定义
public: 所有对象均可以访问。private: 只有自己可以访问。
class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public String toString() {
return String.format("(%d, %d)", x, y);
}
}
7.1.3 类的继承
每个类只能继承一个类。
class ColorPoint extends Point {
private String color;
public ColorPoint(int x, int y, String color) {
super(x, y);
this.color = color;
}
public void setColor(String color) {
this.color = color;
}
public String toString() {
return String.format("(%d, %d, %s)", super.getX(), super.getY(), this.color);
}
}
7.1.4 类的多态
public class Main {
public static void main(String[] args) {
Point point = new Point(3, 4);
Point colorPoint = new ColorPoint(1, 2, "red");
// 多态,同一个类的实例,调用相同的函数,运行结果不同
System.out.println(point.toString());
System.out.println(colorPoint.toString());
}
}
7.2 接口
interface 与 class 类似。主要用来定义类中所需包含的函数。
- 接口也可以继承其他接口,一个类可以实现多个接口。
7.2.1 接口的定义
interface Role {
public void greet();
public void move();
public int getSpeed();
}
7.2.2 接口的继承
每个接口可以继承多个接口。
interface Hero extends Role {
public void attack();
}
7.2.3 接口的实现
每个类可以实现多个接口。
class Zeus implements Hero {
private final String name = "Zeus";
public void attack() {
System.out.println(name + ": Attack!");
}
public void greet() {
System.out.println(name + ": Hi!");
}
public void move() {
System.out.println(name + ": Move!");
}
public int getSpeed() {
return 10;
}
}
7.2.4 接口的多态
class Athena implements Hero {
private final String name = "Athena";
public void attack() {
System.out.println(name + ": Attack!");
}
public void greet() {
System.out.println(name + ": Hi!");
}
public void move() {
System.out.println(name + ": Move!");
}
public int getSpeed() {
return 10;
}
}
public class Main {
public static void main(String[] args) {
Hero[] heros = {new Zeus(), new Athena()};
for (Hero hero: heros) {
hero.greet();
}
}
}
7.3 泛型
类似于 C++ 的 template,Java 的类和接口也可以定义泛型,即同一套函数可以作用于不同的对象类型。
泛型只能使用对象类型,不能使用基本变量类型。
8 常用容器
8.1 List
接口:java.util.List<>
实现:
java.util.ArrayList<>:变长数组java.util.LinkedList<>:双链表
常用函数:
add():在末尾添加一个元素clear():清空size():返回长度isEmpty():是否为空get(i):获取第i个元素set(i, val):将第i个元素设置为val
8.2 栈
类:java.util.Stack<>
常用函数:
push():压入元素pop():弹出栈顶元素,并返回栈顶元素peek():返回栈顶元素size():返回长度empty():栈是否为空clear():清空
8.3 队列
接口:java.util.Queue<>
实现:
java.util.LinkedList<>:双链表java.util.PriorityQueue<>:优先队列- 默认是小根堆,大根堆写法:
new PriorityQueue<>(Collections.reverseOrder())
- 默认是小根堆,大根堆写法:
常用函数:
add():在队尾添加元素remove():删除并返回队头isEmpty():是否为空size():返回长度peek():返回队头clear():清空
8.4 Set
接口:java.util.Set
实现:
java.util.HashSet:哈希表java.util.TreeSet:平衡树
常用函数:
add():添加元素contains():是否包含某个元素remove():删除元素size():返回元素数isEmpty():是否为空clear():清空
java.util.TreeSet 多的函数:
ceiling(key):返回大于等于key的最小元素,不存在则返回nullfloor(key):返回小于等于key的最大元素,不存在则返回null
8.5 Map
接口:java.util.Map
实现:
java.util.HashMap:哈希表java.util.TreeMap:平衡树
常用函数:
put(key, value):添加关键字和其对应的值get(key):返回关键字对应的值containsKey(key):是否包含关键字remove(key):删除关键字size():返回元素数isEmpty():是否为空clear():清空entrySet():获取Map中的所有对象的集合Map.Entry:Map中的对象类型getKey():获取关键字getValue():获取值
java.util.TreeMap 多的函数:
ceilingEntry(key):返回大于等于key的最小元素,不存在则返回nullfloorEntry(key):返回小于等于key的最大元素,不存在则返回null
- 1本网站名称:MuQYY
- 2本站永久网址:www.muqyy.top
- 3本网站的文章部分内容可能来源于网络,仅供大家学习与参考,如有侵权,请联系站长 微信:bwj-1215 进行删除处理。
- 4本站一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
- 5本站一律禁止以任何方式发布或转载任何违法的相关信息,访客发现请向站长举报
- 6本站资源大多存储在云盘,如发现链接失效,请联系我们我们会在第一时间更新。






暂无评论内容