java基础篇

JavaEE基础语法学习笔记


1.Java的变量与常量使用

类似于C#,Java的所有变量和函数都要定义在class中

(1)Java内置数据类型:

类型 字节数 举例
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’

(2)Java常量使用:

使用final修饰

举例:

final int N = 110;

2.Java类型转化

(1)显示转化:

举例:

int x = (int)’A’;

(3)隐式转化:

举例:

double x = 12, y = 4 * 3.3;

3.表达式

与C++、Python3类似,包括+,-,*,/,%等算数运算符, &,|等位运算符, &&,||等逻辑运算符

举例:
int a = 1, b = 2, c = 3;
int x = (a + b) * c;
x ++;

4.Java的输入输出

输入方式1,使用Scanner类,效率较低,输入规模较小时使用。

使用方法:

1
2
3
4
5
6
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,使用BufferReader类与InputStreamReader类,效率较高,输入规模较大时使用。注意需要抛异常。

1
2
3
4
5
6
7
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 使用System.out 输出效率较低,输出规模较小时使用。

1
2
3
4
5
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 效率较高,输出规模较大时使用。注意需要抛异常。

1
2
3
4
5
6
7
8
9
10
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(); // 需要手动刷新缓冲区
}
}

5.Java判断语句

if-else语句

举例:

1
2
3
4
5
6
7
8
9
if(a > b){
System.out.println("a is bigger than b");
}
else if(a < b){
System.out.println("b is bigger than a");
}
else{
System.out.println("a is equal to b");
}

switch语句

举例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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";
}


6.Java循环语句

while循环

例如:

1
2
3
4
5
int i = 0;
while (i < 5) {
System.out.println(i);
i ++ ;
}

do while循环

例如:

1
2
3
4
5
int i = 0;
do {
System.out.println(i);
i ++ ;
} while (i < 5);

do while语句与while语句非常相似。唯一的区别是,do while语句限制性循环体后检查条件。不管条件的值如何,我们都要至少执行一次循环。

for循环

例如:

1
2
3
4
5
6
7
8
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);
}

7.Java数组

数组初始化

初始化定长数组,长度可以是变量,可以在初始化时赋值。

1
2
3
4
5
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中的元素也会改变

数组元素的读取与写入

1
2
3
4
5
6
7
8
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]);
}

多维数组

1
2
3
4
5
6
7
8
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]);

常用API

  • 属性length:返回数组长度,注意不加小括号
  • Arrays.sort():数组排序
  • Arrays.fill(int[] a, int val):填充数组
  • Arrays.toString():将数组转化为字符串
  • Arrays.deepToString():将多维数组转化为字符串

注意:数组不可变长

8.字符串

String类

初始化:

String a = “Hello World”;

String类 常用API:

  1. length():返回长度
  2. split(String regex):分割字符串
  3. indexOf(char c)、indexOf(String str):查找,找不到返回-1
  4. equals():判断两个字符串是否相等,注意不能直接用==
  5. compareTo():判断两个字符串的字典序大小,负数表示小于,0表示相等,正数表示大于
  6. startsWith():判断是否以某个前缀开头
  7. endsWith():判断是否以某个后缀结尾
  8. trim():去掉首位的空白字符
  9. toLowerCase():全部用小写字符
  10. toUpperCase():全部用大写字符
  11. replace(char oldChar, char newChar):替换字符
  12. replace(String oldRegex, String newRegex):替换字符串
  13. substring(int beginIndex, int endIndex):返回[beginIndex, endIndex)中的子串

StringBuilder、StringBuffer

  • String不能被修改,如果打算修改字符串,可以使用StringBuilder和StringBuffer。
  • StringBuffer线程安全,速度较慢;StringBuilder线程不安全,速度较快。

举例;

1
2
3
4
5
6
7
8
9
10
11
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);

9.Java的类

Java源文件声明规则

  • 一个源文件中只能有一个public类。
  • 一个源文件可以有多个非public类。
  • 源文件的名称应该和public类的类名保持一致。
  • 每个源文件中,先写package语句,再写import语句,最后定义类。

Java中类的定义

举例:

  • public: 所有对象均可以访问
  • private: 只有自己可以访问

class Point {
private int x;
private int y;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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);
}

}

Java中类的继承

注意:每个类只能继承一个类。

举例;

class ColorPoint extends Point {
private String color;

1
2
3
4
5
6
7
8
9
10
11
12
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);
}

Java中类的多态

1
2
3
4
5
6
7
8
9
10
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());
}

}

10.Java的接口

interface与class类似。主要用来定义类中所需包含的函数。

接口也可以继承其他接口,一个类可以实现多个接口。

接口的定义

1
2
3
4
5
interface Role {
public void greet();
public void move();
public int getSpeed();
}

接口的继承

每个接口可以继承多个接口

1
2
3
interface Hero extends Role {
public void attack();
}

接口的实现

每个类可以实现多个接口

1
2
3
4
5
class Zeus implements Hero {
private final String name = "Zeus";
public void attack() {
System.out.println(name + ": attack!");
}
1
2
3
4
5
6
7
8
9
10
11
public void greet() {
System.out.println(name + ": Hi!");
}

public void move() {
System.out.println(name + ": Move!");
}

public int getSpeed() {
return 10;
}

}

泛型

类似于C++的template,Java的类和接口也可以定义泛型,即同一套函数可以作用于不同的对象类型。
泛型只能使用对象类型,不能使用基本变量类型。

10.Java常用容器

List

  1. 接口:java.util.List<>。

  2. 实现:

java.util.ArrayList<>:变长数组
java.util.LinkedList<>:双链表

  1. 函数:

add():在末尾添加一个元素
clear():清空
size():返回长度
isEmpty():是否为空
get(i):获取第i个元素
set(i, val):将第i个元素设置为val

  1. 类:java.util.Stack<>

  2. 函数:
    push():压入元素
    pop():弹出栈顶元素,并返回栈顶元素
    peek():返回栈顶元素
    size():返回长度
    empty():栈是否为空
    clear():清空

队列

  1. 接口:java.util.Queue<>

  2. 实现:

java.util.LinkedList<>:双链表
java.util.PriorityQueue<>:优先队列
默认是小根堆,大根堆写法:new PriorityQueue<>(Collections.reverseOrder())

  1. 函数:
    add():在队尾添加元素
    remove():删除并返回队头
    isEmpty():是否为空
    size():返回长度
    peek():返回队头
    clear():清空

Set

  1. 接口:java.util.Set

  2. 实现:
    java.util.HashSet:哈希表
    java.util.TreeSet:平衡树

  3. 函数:
    add():添加元素
    contains():是否包含某个元素
    remove():删除元素
    size():返回元素数
    isEmpty():是否为空
    clear():清空
    java.util.TreeSet多的函数:

​ ceiling(key):返回大于等于key的最小元素,不存在则返回null
​ floor(key):返回小于等于key的最大元素,不存在则返回null

Map

  1. 接口:java.util.Map

  2. 实现:
    java.util.HashMap:哈希表
    java.util.TreeMap:平衡树

  3. 函数:
    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的最小元素,不存在则返回null
    floorEntry(key):返回小于等于key的最大元素,不存在则返回null