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
修饰:
1.3 类型转化
显示转化:int x = (int)'A';
隐式转化:double x = 12, y = 4 * 3.3;
1.4 表达式 与C++、Python3类似:
1 2 3 int a = 1 , b = 2 , c = 3 int x = (a + b) * c x ++
1.5 输入
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,效率较高,输入规模较大时使用。注意需要抛异常。
1 2 3 4 5 6 7 8 9 10 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 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 );
方式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(); } }
2. 判断语句 2.1 if-else语句 与C++、Python中类似。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 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++中类似。
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 28 29 30 31 32 33 34 35 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类似。
1 2 3 4 5 6 7 8 9 10 11 12 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
类似,例如:
1 2 3 4 5 int i = 0 ;while (i < 5 ) { System.out.println(i); i ++ ; }
3.2 do while循环 与C++
、Python
类似,例如:
1 2 3 4 5 int i = 0 ;do { System.out.println(i); i ++ ; } while (i < 5 );
do while语句与while语句非常相似。唯一的区别是,do while语句限制性循环体后检查条件。不管条件的值如何,我们都要至少执行一次循环。
3.3 for循环 与C++、Python类似,例如:
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) { System.out.println(x); }
4. 数组 4.1 初始化 类似c++
初始化定长数组,长度可以是变量,可以在初始化时赋值。
1 2 3 4 5 int [] a = new int [5 ]; int n = 10 ;float [] b = new float [n]; char [] c = {'a' , 'b' , 'c' }; char [] d = c;
4.2 数组元素的读取与写入 类似c++
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]); }
4.3 多维数组 类似c++;
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 ]);
4.4 常用API
属性length
:返回数组长度,注意不加小括号
Arrays.sort()
:数组排序
Arrays.fill(int[] a, int val)
:填充数组
Arrays.toString()
:将数组转化为字符串
Arrays.deepToString()
:将多维数组转化为字符串
数组不可变长
5. 字符串 5.1 String类 初始化:
1 2 3 4 5 6 7 8 String a = "Hello World" ;String b = "My name is" ;String x = b; String c = b + "john" ; String d = "My age is " + 18 ; String str = String.format("My age is %d" , 18 ); String money_str = "123.45" ;double money = Double.parseDouble(money_str);
只读变量,不能修改,例如:
1 2 String a = "Hello " ;a += "World" ;
访问String
中的字符:
1 2 3 4 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)
:查找,找不到返回-1
equals()
:判断两个字符串是否相等,注意不能直接用==
==
判断的是值相等且地址相等
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
线程不安全,速度较快。
1 2 3 4 5 6 7 8 9 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);
6. 函数 Java
的所有变量和函数都要定义在类中。
函数或变量前加static
表示静态对象,类似于全局变量。 静态对象属于class
,而不属于class
的具体实例。
静态函数中只能调用静态函数和静态变量。静态变量是用类名来访问,普通变量是用实例名来访问。
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 28 29 30 31 32 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)); } private static int max (int a, int b) { if (a > b) return a; return b; } 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; } 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; } }
7. 类与接口 7.1 类
一个源文件中只能有一个public
类,可以有多个非public
类。
源文件的名称应该和public
类的类名保持一致。
每个源文件中,先写package
语句,再写import
语句,最后定义类。
public
: 所有对象均可以访问;private
: 只有自己可以访问
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 28 29 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.2 类的继承 每个类只能继承一个类。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 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.3 类的多态 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()); } }
7.4 接口 interface
与class
类似。主要用来定义类中所需包含的函数。
接口也可以继承其他接口,一个类可以实现多个接口。
1 2 3 4 5 interface Role { public void greet () ; public void move () ; public int getSpeed () ; }
每个接口可以继承多个接口,注意类只能继承一个父类(super指代唯一)
1 2 3 interface Hero extends Role { public void attack () ; }
每个类可以实现多个接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 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 ; } }
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 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(); } } }
类似于C++
的template
,Java
的类和接口也可以定义泛型,即同一套函数可以作用于不同的对象类型。
泛型只能使用对象类型,不能使用基本变量类型。
8. 常用容器 8.1 List
java.util.ArrayList<>
:变长数组
java.util.LinkedList<>
:双链表
add()
:在末尾添加一个元素
clear()
:清空
size()
:返回长度
isEmpty()
:是否为空
get(i)
:获取第i个元素
set(i, val)
:将第i个元素设置为val
8.2 栈
push()
:压入元素
pop()
:弹出栈顶元素,并返回栈顶元素
peek()
:返回栈顶元素
size()
:返回长度
empty()
:栈是否为空
clear()
:清空
8.3 队列
java.util.LinkedList<>
:双链表
java.util.PriorityQueue<>
:优先队列
默认是小根堆,大根堆写法:new PriorityQueue<>(Collections.reverseOrder())
add()
:在队尾添加元素
remove()
:删除并返回队头
isEmpty()
:是否为空
size()
:返回长度
peek()
:返回队头
clear()
:清空
8.4 Set
java.util.HashSet<K>
:哈希表
java.util.TreeSet<K>
:平衡树
add()
:添加元素
contains()
:是否包含某个元素
remove()
:删除元素
size()
:返回元素数
isEmpty()
:是否为空
clear()
:清空
java.util.TreeSet
的函数:
ceiling(key)
:返回大于等于key
的最小元素,不存在则返回null
floor(key)
:返回小于等于key
的最大元素,不存在则返回null
8.5 Map
接口:java.util.Map<K, V>
实现:
java.util.HashMap<K, V>
:哈希表
java.util.TreeMap<K, V>
:平衡树
put(key, value)
:添加关键字和其对应的值
get(key)
:返回关键字对应的值
containsKey(key)
:是否包含关键字
remove(key)
:删除关键字
size()
:返回元素数
isEmpty()
:是否为空
clear()
:清空
entrySet()
:获取Map
中的所有对象的集合
Map.Entry<K, V>
:Map
中的对象类型
getKey()
:获取关键字
getValue()
:获取值
java.util.TreeMap<K, V>
的函数:
ceilingEntry(key)
:返回大于等于key
的最小元素,不存在则返回null
floorEntry(key)
:返回小于等于key
的最大元素,不存在则返回null