HelloWorld案例 1 2 3 4 5 6 7 public class HelloWorld { public static void main (String[] args) { System.Out.prinln("HelloWorld" ); } }
关键字class 被 Java 赋予了特定含义的英文单词,关键字都是字母小写开头。
1 2 public class HelloWorld {}
字面量
字面量类型
说明
程序中的写法
整数
不带小数的数字
666,-88
小数
带小数的数字
13.14,-5.21
字符
必须使用单引号,有且仅能一个字符
‘A’,‘0’, ‘我’
字符串
必须使用双引号,内容可有可无
“HelloWorld”,“黑马程序员”
布尔值
布尔值,表示真假,只有两个值:true,false
true 、false
空值
一个特殊的值,空值
值是:null
特殊符号
转义字符
名称
说明
示例
\n
换行
光标移到下一行开头
"A\nB"→ A、B 分两行
\t
水平制表符
对齐到8n+1列
"A\tB"→ B出现在第9列
\
反斜杠
表示\本身
"C:\\dir" → C:\dir
"
双引号
在字符串中嵌入”
"say \"hi\""→ say "hi"
'
单引号
在字符常量中嵌入’
'\''→ 单引号字符
\r
回车
光标回到当前行首(不换行)
"ABC\rX"→ 输出 XBC
变量 1 2 3 4 5 6 7 8 9 10 int a = 1 , b = 2 ;int a = 1 ;int a; String s; boolean flag; System.out.println(a);
数据类型 1 2 3 4 5 6 7 8 9 10 11 12 13 14 public class Demo { public static void main (String[] args) { int bin = 0b1010 ; int oct = 012 ; int dec = 10 ; int hex = 0xA ; System.out.println(bin == oct && oct == dec && dec == hex); } }
基本数据类型
数据类型
关键字
内存占用
取值范围
整数
byte
1
负的2的7次方 ~ 2的7次方-1(-128~127)
short
2
负的2的15次方 ~ 2的15次方-1(-32768~32767)
int
4
负的2的31次方 ~ 2的31次方-1
long
8
负的2的63次方 ~ 2的63次方-1
浮点数
float
4
1.401298e-45 ~ 3.402823e+38
double
8
4.9000000e-324 ~ 1.797693e+308
字符
char
2
0-65535
布尔
boolean
1
true,false
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 36 37 38 39 40 41 42 43 public class VariableDemo3 { public static void main (String[] args) { byte a = 10 ; System.out.println(a); short b = 20 ; System.out.println(b); int c = 30 ; System.out.println(c); long d = 123456789123456789L ; System.out.println(d); float e = 10.1F ; System.out.println(e); double f = 20.3 ; System.out.println(f); char g = 'a' ; System.out.println(g); boolean h = true ; System.out.println(h); StringBuilder sb = new StringBuilder (); var sb = new StringBuilder (); final double PI = 3.14 ; } }
标识符
必须由数字、字母、下划线_、美元符号$组成。
数字不能开头
不能是关键字
区分大小写的
键盘录入
1 2 3 4 5 6 7 8 9 10 11 import java.util.Scanner;public class ScannerDemo {public static void main (String[] args) {Scanner sc = new Scanner (System.in);int i = sc.nextInt();System.out.println(i); } }
结构分类 project(项目、工程)
module(模块)
package(包)
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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 System.out.println( 10 / 3 ); System.out.println(10.0 / 3 ); int sum = 2147483640 + 15 ; System.out.println(15 % 2 ); double d = 10 ;System.out.println(d); public class OperatorDemo2 { public static void main (String[] args) { double a = 12.3 ; int b = (int ) a; System.out.println(b); } } 1 + "abc" + 1 1 + 2 + "abc" + 2 + 1 char c = 'a' ;int result = c + 0 ;System.out.println(result); int a = 0 ;System.out.println(++a); System.out.println(a++); byte a = 10 ;byte b = 20 ;a = (byte )(a + b) char a = '1' ;int b = 49 ;System.out.println(a == b); System.out.println(true & true ); System.out.println(true | false ); System.out.println(true ^ true ); System.out.println(!false );
原码、反码、补码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
输出printf 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 int num = 42 ;double pi = 3.1415926 ;String name = "Java" ;System.out.printf("%d | %.2f | %s%n" , num, pi, name); System.out.printf("%.2f%n" , pi); System.out.printf("%.0f%n" , pi); System.out.printf("%.3s%n" , name); System.out.printf("|%8d|%n" , num); System.out.printf("|%-8d|%n" , num); System.out.printf("|%08d|%n" , num); double price = 12900000 ;System.out.printf("金额: %,10.2f%n" , price);
流程控制语句
顺序结构没有特定的语法结构,按照代码的先后顺序,依次执行。
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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 if (关系表达式) { 语句体; } else if (关系表达式) { 语句体; } else { 语句体; } switch (表达式) { case 1 : 语句体1 ; break ; case 2 : 语句体2 ; break ; ... default : 语句体n+1 ; break ; } int number = 10 ;switch (number) { case 1 -> System.out.println("一" ); case 2 -> System.out.println("二" ); case 3 -> System.out.println("三" ); case 4 -> { System.out.println("三" ); System.out.println("多行" ); } default -> System.out.println("其他" ); } String fruit = "apple" ;switch (fruit) { case "apple" : System.out.println("Selected apple" ); break ; default : System.out.println("No fruit selected" ); break ; } public class Main { public static void main (String[] args) { String fruit = "apple" ; int opt = switch (fruit) { case "apple" -> 1 ; case "pear" , "mango" -> 2 ; default -> { int code = fruit.hashCode(); yield code; } }; System.out.println("opt = " + opt); } }
循环结构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 for (初始化语句;条件判断语句;条件控制语句) { 循环体语句; } 初始化语句; while (条件判断语句){ 循环体; 条件控制语句; } 初始化语句; do { 循环体; 条件控制语句; }while (条件判断语句);
循环高级 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 36 37 38 39 40 for (;;){ System.out.println("循环执行一直在打印内容" ); } while (true ){ System.out.println("循环执行一直在打印内容" ); } do { System.out.println("循环执行一直在打印内容" ); }while (true ); int [] ns = { 1 , 4 , 9 , 16 , 25 };for (int n : ns) { System.out.println(n); } break continue import java.util.Random;public class RandomDemo1 { public static void main (String[] args) { Random r = new Random (); int number = r.nextInt(100 ); System.out.println(number); } } int number = r.nextInt(21 ) + 5
数组 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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 int [] array = new int []{1 , 2 , 3 };int arrry[] = new int []{1 , 2 , 3 };int [] arr = {1 , 2 , 3 }System.out.println(array); System.out.println(array[0 ]); System.out.println(array.length); array[0 ] = 0 ; int [] agesArr = new int [3 ];int [] arr = {1 ,2 ,3 };System.out.println(arr[3 ]); System.out.print(); int [] ns = { 1 , 4 , 9 , 16 , 25 };for (int n : ns) { System.out.println(n); } int [] arr = {1 ,2 ,3 ,4 ,5 };for (int i = 0 ,j = arr.length - 1 ; i < j; i++,j--){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } for (int i = 0 ; i < arr.length; i++) { System.out.print(arr[i] + " " ); } import java.util.Arrays;System.out.println(Arrays.toString(ns)); System.out.println(Arrays.deepToString(ns)); int [][] arr = new int [2 ][]; int [] arr1 = {1 ,2 };int [] arr2 = {3 ,4 };arr[0 ] = arr1; arr[1 ] = arr2; int [][] arr = new int [1 ][1 ];System.out.println(Arrays.deepToString(arr)); arr[0 ] = new int []{1 , 2 }; System.out.println(Arrays.deepToString(arr));
方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public static 数据类型 方法名 ( 参数 ) { return 数据 ; } public class Demo { public static void main (String[] args) { test(); } public static void test () { System.out.println("test" ); } } public static void test (double r, double h) {} public static void test (double h, double r) {}
面向对象 类的定义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public class 类名 { 变量1 的数据类型 变量1 ; 变量2 的数据类型 变量2 ; … 方法1 ; 方法2 ; }
封装 对象代表什么,就得封装对应的数据,并提供数据对应的行为
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class Student { private int age; public void setAge (int a) { age = a; } public int getAge () { return age; } }
this关键字 this 修饰的变量用于指代成员变量,其主要作用是(区分局部变量和成员变量的重名问题)
方法的形参如果与成员变量同名,不带 this 修饰的变量指的是形参,而不是成员变量
方法的形参没有与成员变量同名,不带 this 修饰的变量指的是成员变量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public class Student { private String name; private int age; 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 show () { System.out.println(name + "," + age); } }
构造方法 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 class Student { private String name; private int age; public Student () {} public Student (String name) { this .name = name; } public Student (int age) { this .age = age; } public Student (String name,int age) { this .name = name; this .age = age; } public void show () { System.out.println(name + "," + age); } }
可变参数 1 2 3 4 5 6 7 8 9 10 11 12 13 class Group { private String[] names; public void setNames (String... names) { this .names = names; } } Group g = new Group ();g.setNames("Xiao Ming" , "Xiao Hong" , "Xiao Jun" ); g.setNames("Xiao Ming" , "Xiao Hong" ); g.setNames();
标准类制作(JavaBean) 💡 1.类名需要见名知意 2.成员变量使用 private 修饰 3.提供至少两个构造方法(无参构造方法、带全部参数的构造方法) 4.get和set方法:提供每一个成员变量对应的 setXxx()/getXxx() 5.如果还有其他行为,也需要写上
键盘录入 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 Scanner sc = new Scanner (System.in);int i = sc.nextInt(); double d = sc.nextDouble(); String s = sc.next(); String s1 = sc.nextLine(); String s1 = sc.next();String s2 = sc.next();System.out.println(s1); System.out.println(s2); int i = sc.nextInt();String s = sc.nextLine();
String String 类代表字符串,Java 程序中的所有字符串文字(例如“abc”)都被实现为此类的实例。也就是说,Java 程序中所有的双引号字符串,都是 String 类的对象。String 类在 java.lang 包下,所以使用的时候不需要导包!
字符串不可变,它们的值在创建后不能被更改
虽然 String 的值是不可变的,但是它们可以被共享
字符串效果上相当于字符数组( char[] ),但是底层原理是字节数组( byte[] )
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 public class StringDemo01 { String str; public static void main (String[] args) { String s1 = new String (); System.out.println("s1:" + s1); char [] chs = {'a' , 'b' , 'c' }; String s2 = new String (chs); System.out.println("s2:" + s2); byte [] bys = {97 , 98 , 99 }; String s3 = new String (bys); System.out.println("s3:" + s3); String s4 = "abc" ; System.out.println("s4:" + s4); String s = """ SELECT * FROM users WHERE id > 100 ORDER BY name DESC """ ; } }
方法
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 36 37 38 39 40 41 42 43 44 char [] chs = {'a' , 'b' , 'c' };String s1 = new String (chs);String s2 = new String (chs);String s3 = "abc" ;String s4 = "abc" ;System.out.println(s1 == s2); System.out.println(s1 == s3); System.out.println(s3 == s4); System.out.println(s1.equals(s2)); System.out.println(s1.equals(s3)); System.out.println(s3.equals(s4)); for (int i = 0 ; i < str.length(); i++) { char c = str.charAt(i); System.out.println(c); } "aaa" .replace("a" , "b" ); "foo123bar456" .replaceAll("\\d+" , "#" ); "a$b" .replaceAll("\\$" , Matcher.quoteReplacement("$" )); "aaa" .replaceFirst("a" , "b" );
StringBuilder StringBuilder 可以看成是一个容器,创建之后里面的内容是可变的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 new StringBuilder () new StringBuilder (256 ) new StringBuilder ("init" ) sb.append("str" ) sb.insert(2 , "ab" ) sb.delete(1 , 3 ) sb.deleteCharAt(1 ) sb.replace(1 , 3 , "xy" ) sb.reverse() sb.setCharAt(0 , 'A' ) sb.length() sb.charAt(0 ) sb.indexOf("ab" ) sb.substring(1 , 3 ) sb.toString()
StringJoiner
StringJoiner跟StringBuilder一样,也可以看成是一个容器,创建之后里面的内容是可变的。
作用:提高字符串的操作效率,而且代码编写特别简洁,但是目前市场上很少有人用。
JDK8出现的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 new StringJoiner ("," ) new StringJoiner ("," , "[" , "]" ) new StringJoiner (delimiter, prefix, suffix)add("a" ).add("b" ).add("c" ) merge(otherJoiner) toString() length() setEmptyValue("N/A" )
ArrayList
提供一种存储空间可变的存储模型,存储的数据容量可以发生改变
长度可以变化,只能存储引用数据类型。
泛型:用于约束集合中存储元素的数据类型
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 36 37 38 ArrayList<String> list = new ArrayList <>(); ArrayList<Integer> nums = new ArrayList <>(100 ); boolean b1 = list.add("A" ); void list.add(1 , "B" ); boolean b2 = list.addAll(otherList); boolean b3 = list.remove("A" ); String old2 = list.remove(1 ); boolean b4 = list.removeAll(c); void list.clear(); String old3 = list.set(1 , "C" ); String val = list.get(1 ); int idx = list.indexOf("A" ); int lidx = list.lastIndexOf("A" ); boolean b5 = list.contains("A" ); int size = list.size(); boolean b6 = list.isEmpty(); for (String s : list) { } list.forEach(s -> System.out.println(s)); Object[] arr1 = list.toArray(); String[] arr2 = list.toArray(new String [0 ]); List<String> sub = list.subList(1 , 3 );
基本类型转包装类 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 Integer a = 100 ; Long b = 200L ; Boolean c = true ; int x = a; long y = b; boolean z = c; Integer n1 = Integer.valueOf("123" ); int n2 = Integer.parseInt("123" ); long n3 = Long.parseLong("456" ); double n4 = Double.parseDouble("3.14" ); boolean n5 = Boolean.parseBoolean("true" ); String s1 = String.valueOf(n1); String s2 = Integer.toString(123 ); String s3 = n1.toString();
static关键字 1 2 3 4 5 6 7 8 9 10 11 class Foo { static int count = 0 ; public static void main (String[] arg) {} } Foo foo = new Foo ();System.out.println(foo.count); System.out.println(Foo.count);
继承 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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 class 父类 { ... } class 子类 extends 父类 { ... } class Fu { public void show () {} public Number getNumber () { return 0 ; } } class Zi extends Fu { @Override public void show () { super .show(); } public Integer getNumber () { return 100 ; } } class Person { public Person () {} } class Student extends Person { public Student () { super (); } } class Student { private String name ; public Student () { this ("徐干" ); } public Student (String name) { this .name = name ; } }
多态 是指同一行为,具有多个不同表现形式
前提
有继承或者实现关系
方法的重写【意义体现:不重写,无意义】
父类引用指向子类对象【格式体现】
父类类型:指子类对象继承的父类类型,或者实现的父接口类型。
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 36 37 38 39 40 41 42 43 44 45 46 47 class Person { private String name; public Person (String name) { this .name = name; } public String getName () { return name; } public void show () { System.out.println(name); } } class Student extends Person { public Student (String name) { super (name); } @Override public void show () { System.out.println("学生:" + getName()); } } class Teacher extends Person { public Teacher (String name) { super (name); } @Override public void show () { System.out.println("老师:" + getName()); } } public class Test { public static void main (String[] args) { register(new Student ("张三" )); register(new Teacher ("王建国" )); } public static void register (Person p) { p.show(); } }
多态特点 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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 Fu f = new Zi ();System.out.println(f.name); f.show(); class Animal { public void eat () { System.out.println("动物吃东西!" ); } } class Cat extends Animal { public void eat () { System.out.println("吃鱼" ); } public void catchMouse () { System.out.println("抓老鼠" ); } } class Dog extends Animal { public void eat () { System.out.println("吃骨头" ); } } class Test { public static void main (String[] args) { Animal a = new Cat (); a.eat(); a.catchMouse(); } } public class Test { public static void main (String[] args) { Animal a = new Cat (); a.eat(); Cat c = (Cat)a; c.catchMouse(); } } if (a instanceof Cat){ Cat c = (Cat)a; c.catchMouse(); } else if (a instanceof Dog){ Dog d = (Dog)a; d.watchHouse(); } if (a instanceof Dog d){ d.lookHome(); }else if (a instanceof Cat c){ c.catchMouse(); }
包 包在操作系统中其实就是一个文件夹。
包名一般是公司域名的倒写。例如:www.xxx.com 包名就可以定义成 com.xxx.技术名称。
包名必须用 . 连接。
包名的每个路径名必须是一个合法的标识符,而且不能是 Java 的关键字。
导包规则
使用同一个包中的类时,不需要导包。
使用 java.lang 包中的类时,不需要导包。
其他情况都需要导包。
如果同时使用两个包中的同名类,需要用全类名
final 不可改变,最终的含义。可以用于修饰类、方法和变量。
类:被修饰的类,不能被继承。
方法:被修饰的方法,不能被重写。
变量:被修饰的变量,有且仅能被赋值一次。
权限修饰符 💡 修饰符
private
可见范围:只能在本类中访问
能修饰:变量 √ 方法 √ 内部类 √ 顶级类 ×
默认(不写)
可见范围:本类 + 同一个包内可以访问
能修饰:变量 √ 方法 √ 内部类 √ 顶级类 √
protected
可见范围:本类 + 同一个包 + 不同包的子类可以访问
能修饰:变量 √ 方法 √ 内部类 √ 顶级类 ×
public
可见范围:任何地方都可以访问
能修饰:变量 √ 方法 √ 内部类 √ 顶级类 √
代码块 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 public void method () { { int temp = 10 ; } } class Student { { System.out.println("构造代码块执行" ); } public Student () { System.out.println("无参构造执行" ); } } class Config { static int maxCount; static { maxCount = 100 ; System.out.println("静态代码块执行" ); } }
抽象类 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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 abstract class Animal { String name; abstract void eat () ; void sleep () { System.out.println("睡觉中..." ); } } class Dog extends Animal { @Override void eat () { System.out.println("狗啃骨头" ); } } Animal a = new Dog (); a.eat(); abstract class Shape { String color; public Shape (String color) { this .color = color; } } abstract class Util { static final double PI = 3.14 ; static void help () { System.out.println("工具方法" ); } abstract void draw () ; } class Parent { void a () { System.out.println("a" ); } } abstract class Child extends Parent { abstract void b () ; } class GrandChild extends Child { void b () { System.out.println("b" ); } }
接口 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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 interface Animal { void eat () ; public abstract void run () ; int MAX_AGE = 100 ; default void sleep () { System.out.println("睡觉" ); test1(); } static void info () { System.out.println("这是动物接口" ); test2(); } private void test1 () {} private static void test2 () {} } class Dog implements Animal { @Override public void eat () { System.out.println("吃骨头" ); } @Override public void run () { System.out.println("跑" ); } } public class Main { public static void main (String[] args) { Dog d = new Dog (); d.eat(); d.sleep(); Animal.info(); System.out.println(Animal.MAX_AGE); } } interface A { void a () ; }interface B { void b () ; }interface C extends A , B { void c () ; }class Parent { void p () {} }class Child extends Parent implements A , B { public void a () {} public void b () {} } interface A { void test () ; }interface B { void test () ; }class C implements A , B { public void test () {} } interface A { int test () ; }interface B { String test () ; }class C implements A , B { }
内部类 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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 public class Outer { private int x = 10 ; private static int y = 20 ; class MemberInner { private int x = 10 ; static int a = 1 ; void show () { System.out.println("成员内部类: x=" + x + ", y=" + y); System.out.println(Outer.this .x); } } static class StaticInner { void show () { System.out.println("静态内部类: y=" + y); } } void method () { int local = 30 ; class LocalInner { void show () { System.out.println("局部内部类: local=" + local); } } new LocalInner ().show(); Runnable r = new Runnable () { public void run () { System.out.println("匿名内部类: local=" + local); } }; r.run(); int b = 10 ; b = 20 ; Runnable r2 = new Runnable () { public void run () { System.out.println(b); } }; } public static void main (String[] args) { new Outer ().new MemberInner ().show(); new Outer .StaticInner().show(); new Outer ().method(); } }
Math 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 public static int abs (int a) public static double ceil (double a) public static double floor (double a) public static int round (float a) public static int max (int a,int b) public static int min (int a,int b) public static double pow (double a,double b) public static double random () System.out.println(Math.abs(-5 )); System.out.println(Math.abs(Integer.MIN_VALUE)); Math.absExact(Integer.MIN_VALUE); System.out.println(Math.ceil(3.2 )); System.out.println(Math.floor(3.8 )); System.out.println(Math.round(3.5f )); System.out.println(Math.max(10 , 20 )); System.out.println(Math.min(10 , 20 )); System.out.println(Math.pow(2 , 3 )); System.out.println(Math.random());
System 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public static long currentTimeMillis () public static void exit (int status) public static native void arraycopy (Object src, int srcPos, Object dest, int destPos, int length) ; long start = System.currentTimeMillis();for (int i = 0 ; i < 10000 ; i++) { } long end = System.currentTimeMillis();System.out.println("耗时:" + (end - start) + "ms" ); int [] src = {1 , 2 , 3 , 4 , 5 };int [] dest = new int [5 ];System.arraycopy(src, 1 , dest, 0 , 3 ); System.out.println(java.util.Arrays.toString(dest));
Runtime 表示虚拟机的运行环境
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 public static Runtime getRuntime () public void exit (int status) public int availableProcessors () public long maxMemory () public long totalMemory () public long freeMemory () public Process exec (String command) Runtime r1 = Runtime.getRuntime();Runtime.getRuntime().exit(0 ); System.out.println(Runtime.getRuntime().availableProcessors()); System.out.println(Runtime.getRuntime().maxMemory() / 1024 / 1024 ); System.out.println(Runtime.getRuntime().totalMemory() / 1024 / 1024 ); System.out.println(Runtime.getRuntime().freeMemory() / 1024 / 1024 ); Runtime.getRuntime().exec("shutdown -s -t 3600" );
Object 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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 public String toString () public boolean equals (Object obj) protected Object clone () Student s1 = new Student ("张三" , 20 );System.out.println(s1); Student s2 = new Student ("张三" , 20 );System.out.println(s1 == s2); class Student implements Cloneable { String name; int age; public Student (String name, int age) { this .name = name; this .age = age; } @Override public String toString () { return "Student{name='" + name + "', age=" + age + "}" ; } @Override public boolean equals (Object obj) { if (this == obj) return true ; if (obj == null || getClass() != obj.getClass()) return false ; Student s = (Student) obj; return age == s.age && name.equals(s.name); } @Override protected Object clone () throws CloneNotSupportedException { return super .clone(); } } public class ObjectDemo { public static void main (String[] args) throws CloneNotSupportedException { Student s1 = new Student ("张三" , 20 ); System.out.println(s1.toString()); Student s2 = new Student ("张三" , 20 ); System.out.println(s1.equals(s2)); Student s3 = (Student) s1.clone(); System.out.println(s3 == s1); System.out.println(s3.equals(s1)); } }
Objects 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 public static String toString (Object o) public static boolean equals (Object a, Object b) public static boolean isNull (Object obj) public static boolean nonNull (Object obj) String s = null ;System.out.println(Objects.toString(s)); System.out.println(Objects.toString(s, "默认值" )); String a = "hello" ;String b = null ;System.out.println(Objects.equals(a, b)); System.out.println(Objects.equals(b, null )); System.out.println(Objects.isNull(b)); System.out.println(Objects.nonNull(a));
浅拷贝深拷贝
BigInteger 1 2 3 4 5 6 7 8 9 10 11 12 13 14 public BigInteger (int num, Random rnd) public BigInteger (String val) public BigInteger (String val, int radix) public static BigInteger valueOf (long val) BigInteger r = new BigInteger (128 , new Random ());BigInteger a = new BigInteger ("123456789012345678901234567890" );BigInteger b = new BigInteger ("FF" , 16 ); BigInteger c = BigInteger.valueOf(100 );
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 36 37 38 39 40 41 42 public BigInteger add (BigInteger val) public BigInteger subtract (BigInteger val) public BigInteger multiply (BigInteger val) public BigInteger divide (BigInteger val) public BigInteger[] divideAndRemainder(BigInteger val) public boolean equals (Object x) public BigInteger pow (int exponent) public BigInteger max/min(BigInteger val) public int intValue (BigInteger val) BigInteger x = BigInteger.valueOf(17 );BigInteger y = BigInteger.valueOf(5 );x.add(y); x.subtract(y); x.multiply(y); x.divide(y); x.remainder(y); BigInteger[] qr = x.divideAndRemainder(y); x.equals(y); x.pow(3 ); x.max(y); x.min(y); int v = x.intValue();
BigDecimal 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 36 37 38 39 40 41 42 43 44 45 46 47 48 BigDecimal a = new BigDecimal ("0.1" );BigDecimal b = new BigDecimal ("0.2" );BigDecimal c = new BigDecimal (0.1 ); BigDecimal d = BigDecimal.valueOf(0.1 ); BigDecimal x = new BigDecimal ("10" );BigDecimal y = new BigDecimal ("3" );x.add(y); x.subtract(y); x.multiply(y); x.divide(y, 2 , RoundingMode.HALF_UP); x.divide(y, 4 , RoundingMode.DOWN); x.divide(y, 2 , RoundingMode.CEILING); x.divide(y, 2 , RoundingMode.FLOOR); new BigDecimal ("1.0" ).equals(new BigDecimal ("1.00" )); new BigDecimal ("1.0" ).compareTo(new BigDecimal ("1.00" ));
正则表达式 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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 System.out.println(qq.matches("[1-9]\\d{5,19}" )); String regex = "[a-z&&[def]]" ;"a" .matches(regex); "d" .matches(regex); import java.util.regex.Matcher;import java.util.regex.Pattern;public class RegexDemo { public static void main (String[] args) { Pattern pattern = Pattern.compile("\\d+" ); Matcher matcher = pattern.matcher("abc123def456ghi789" ); while (matcher.find()) { System.out.println(matcher.group()); System.out.println("起始: " + matcher.start()); System.out.println("结束: " + matcher.end()); } } } String s = "Java自从95年问世以来,经历了很多版本,目前企业中用的最多的是Java8和Java11," + "因为这两个是长期支持版本,下一个长期支持版本是Java17,相信在未来不久Java17也会逐渐登上历史舞台" ;String regex1 = "((?i)Java)(?=8|11|17)" ; String regex2 = "((?i)Java)(8|11|17)" ;String regex3 = "((?i)Java)(?:8|11|17)" ;String regex4 = "((?i)Java)(?!8|11|17)" ;Matcher m1 = Pattern.compile("(a)(?:b)(c)" ).matcher("abc" );m1.find(); m1.group(1 ); m1.group(2 ); m1.group(); Matcher m2 = Pattern.compile("\\d+(?=元)" ).matcher("99元" );m2.find(); m2.group(); Matcher m3 = Pattern.compile("\\d+(?!元)" ).matcher("99元 5kg" );while (m3.find()) { }m3.group(); "99元" .replaceAll("\\d+元" , "" ); "99元" .replaceAll("\\d+(?=元)" , "" ); Matcher m5 = Pattern.compile("(?=(\\d+)元)" ).matcher("99元" );m5.find(); m5.group(); m5.group(1 ); "abc12345" .matches("^(?=.*\\d)(?=.*[a-z]).{8,}$" );
String使用正则表达式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 String s = "小诗诗dqwefqwfqwfwq12312小丹丹dqwefqwfqwfwq12312小惠惠" ;String[] arr = s.split("[\\w&&[^_]]+" ); for (int i = 0 ; i < arr.length; i++) { System.out.println(arr[i]); } String s = "小诗诗dqwefqwfqwfwq12312小丹丹dqwefqwfqwfwq12312小惠惠" ;String result1 = s.replaceAll("[\\w&&[^_]]+" , "vs" );System.out.println(result1);
正则表达式分组 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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 String regex1 = "(.).+\\1" ;System.out.println("a123a" .matches(regex1)); System.out.println("b456b" .matches(regex1)); System.out.println("17891" .matches(regex1)); System.out.println("&abc&" .matches(regex1)); System.out.println("a123b" .matches(regex1)); System.out.println("--------------------------" ); String regex2 = "(.+).+\\1" ;System.out.println("abc123abc" .matches(regex2)); System.out.println("b456b" .matches(regex2)); System.out.println("123789123" .matches(regex2)); System.out.println("&!@abc&!@" .matches(regex2)); System.out.println("abc123abd" .matches(regex2)); System.out.println("---------------------" ); String regex3 = "((.)\\2*).+\\1" ;System.out.println("aaa123aaa" .matches(regex3)); System.out.println("bbb456bbb" .matches(regex3)); System.out.println("111789111" .matches(regex3)); System.out.println("&&abc&&" .matches(regex3)); System.out.println("aaa123aab" .matches(regex3)); String str = "我要学学编编编编程程程程程程" ;String result = str.replaceAll("(.)\\1+" , "$1" );System.out.println(result); String regex2 = "[1-9]\\d{16}(\\d Xx)\\1" ;System.out.println("41080119930228457x" .matches(regex2));
Date类 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 import java.util.Date;public class DateDemo { public static void main (String[] args) { Date now = new Date (); Date date = new Date (1700000000000L ); long time = now.getTime(); now.setTime(1700000000000L ); boolean before = date.before(now); boolean after = date.after(now); int cmp = date.compareTo(now); long oneDay = 24 * 60 * 60 * 1000L ; Date tomorrow = new Date (now.getTime() + oneDay); Date lastWeek = new Date (now.getTime() - 7 * oneDay); System.out.println(now.toString()); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 import java.text.SimpleDateFormat;import java.util.Date;SimpleDateFormat sdf1 = new SimpleDateFormat (); SimpleDateFormat sdf2 = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss" ); Date now = new Date ();String str = sdf2.format(now); Date date = sdf2.parse("2026-09-09 19:14:00" );
Calendar 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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 import java.util.Calendar;public class CalendarDemo { public static void main (String[] args) { Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH) + 1 ; int day = c.get(Calendar.DAY_OF_MONTH); int hour = c.get(Calendar.HOUR); int hour24 = c.get(Calendar.HOUR_OF_DAY); int minute = c.get(Calendar.MINUTE); int second = c.get(Calendar.SECOND); int week = c.get(Calendar.DAY_OF_WEEK); System.out.printf("当前:%d-%02d-%02d %02d:%02d:%02d 星期%d%n" , year, month, day, hour, minute, second, week); c.set(Calendar.YEAR, 1998 ); c.set(Calendar.MONTH, 2 ); c.set(Calendar.DAY_OF_MONTH, 18 ); System.out.println("1998-03-18是星期" + "日一二三四五六" .charAt(c.get(Calendar.DAY_OF_WEEK) - 1 )); c.setTimeInMillis(System.currentTimeMillis()); c.add(Calendar.DAY_OF_MONTH, 200 ); System.out.printf("200天后:%d-%02d-%02d%n" , c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1 , c.get(Calendar.DAY_OF_MONTH)); long millis = c.getTimeInMillis(); c.setTimeInMillis(millis); c.add(Calendar.MONTH, -1 ); int maxDay = c.getActualMaximum(Calendar.DAY_OF_MONTH); int minDay = c.getActualMinimum(Calendar.DAY_OF_MONTH); System.out.printf("上月最后一天是%d号,时间戳:%d%n" , maxDay, millis); java.util.Date date = c.getTime(); c.setTime(date); } } Calendar c1 = Calendar.getInstance();c1.set(2026 , 0 , 31 ); c1.add(Calendar.MONTH, 1 ); Calendar c2 = Calendar.getInstance();c2.set(2026 , 0 , 31 ); c2.set(Calendar.MONTH, 1 );
JDK8时间相关类
JDK8时间类类名
作用
ZoneId
时区
Instant
时间戳
ZoneDateTime
带时区的时间
DateTimeFormatter
用于时间的格式化和解析
LocalDate
年、月、日
LocalTime
时、分、秒
LocalDateTime
年、月、日、时、分、秒
Duration
时间间隔(秒,纳,秒)
Period
时间间隔(年,月,日)
ChronoUnit
时间间隔(所有单位)
ZoneId 时区 1 2 3 4 5 6 7 8 9 10 11 12 13 Set<String> zoneIds = ZoneId.getAvailableZoneIds(); System.out.println(zoneIds.size()); ZoneId zoneId = ZoneId.systemDefault();ZoneId zoneId1 = ZoneId.of("Asia/Pontianak" );
Instant 时间戳 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 36 37 38 39 40 41 42 43 44 Instant now = Instant.now();System.out.println(now); Instant instant1 = Instant.ofEpochMilli(0L );System.out.println(instant1); Instant instant2 = Instant.ofEpochSecond(1L );System.out.println(instant2); Instant instant3 = Instant.ofEpochSecond(1L , 1000000000L );System.out.println(instant3); ZonedDateTime time = Instant.now().atZone(ZoneId.of("Asia/Shanghai" ));System.out.println(time); Instant instant4=Instant.ofEpochMilli(0L ); Instant instant5 = Instant.ofEpochMilli(1000L );boolean result1=instant4.isBefore(instant5);System.out.println(result1); boolean result2 = instant4.isAfter(instant5);System.out.println(result2); Instant instant6 = Instant.ofEpochMilli(3000L );System.out.println(instant6); Instant instant7 = instant6.minusSeconds(1 );System.out.println(instant7);
ZoneDateTime 带时区的时间 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 ZonedDateTime now = ZonedDateTime.now();System.out.println(now); ZonedDateTime time1 = ZonedDateTime.of(2023 , 10 , 1 , 11 , 12 , 12 , 0 , ZoneId.of("Asia/Shanghai" ));System.out.println(time1); Instant instant = Instant.ofEpochMilli(0L );ZoneId zoneId = ZoneId.of("Asia/Shanghai" );ZonedDateTime time2 = ZonedDateTime.ofInstant(instant, zoneId);System.out.println(time2); ZonedDateTime time3 = time2.withYear(2000 );System.out.println(time3); ZonedDateTime time4 = time3.minusYears(1 );System.out.println(time4); ZonedDateTime time5 = time4.plusYears(1 );System.out.println(time5);
1 2 3 4 5 6 7 8 9 10 11 ZonedDateTime time = Instant.now().atZone(ZoneId.of("Asia/Shanghai" ));DateTimeFormatter dtf1=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm;ss EE a" ); System.out.println(dtf1.format(time));
LocalDate 年、月、日 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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 LocalDate nowDate = LocalDate.now();LocalDate ldDate = LocalDate.of(2023 , 1 , 1 );System.out.println("指定日期:" + ldDate); System.out.println("=============================" ); int year = ldDate.getYear();System.out.println("year: " + year); Month m = ldDate.getMonth();System.out.println(m); System.out.println(m.getValue()); int month = ldDate.getMonthValue();System.out.println("month: " + month); int day = ldDate.getDayOfMonth();System.out.println("day:" + day); int dayofYear = ldDate.getDayOfYear();System.out.println("dayOfYear:" + dayofYear); DayOfWeek dayOfWeek = ldDate.getDayOfWeek();System.out.println(dayOfWeek); System.out.println(dayOfWeek.getValue()); System.out.println(ldDate.isBefore(ldDate)); System.out.println(ldDate.isAfter(ldDate)); LocalDate withLocalDate = ldDate.withYear(2000 );System.out.println(withLocalDate); LocalDate minusLocalDate = ldDate.minusYears(1 );System.out.println(minusLocalDate); LocalDate plusLocalDate = ldDate.plusDays(1 );System.out.println(plusLocalDate); LocalDate birDate = LocalDate.of(2000 , 1 , 1 );LocalDate nowDate1 = LocalDate.now();MonthDay birMd = MonthDay.of(birDate.getMonthValue(), birDate.getDayOfMonth());MonthDay nowMd = MonthDay.from(nowDate1);System.out.println("今天是你的生日吗? " + birMd.equals(nowMd));
LocalTime 时、分、秒 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 LocalTime nowTime = LocalTime.now();System.out.println("今天的时间:" + nowTime); int hour = nowTime.getHour();System.out.println("hour: " + hour); int minute = nowTime.getMinute();System.out.println("minute: " + minute); int second = nowTime.getSecond();System.out.println("second:" + second); int nano = nowTime.getNano();System.out.println("nano:" + nano); System.out.println("------------------------------------" ); System.out.println(LocalTime.of(8 , 20 )); System.out.println(LocalTime.of(8 , 20 , 30 )); System.out.println(LocalTime.of(8 , 20 , 30 , 150 )); LocalTime mTime = LocalTime.of(8 , 20 , 30 , 150 );System.out.println(nowTime.isBefore(mTime)); System.out.println(nowTime.isAfter(mTime)); System.out.println(nowTime.withHour(10 )); System.out.println(nowTime.plusHours(10 ));
LocalDateTime 年、月、日、时、分、秒 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 LocalDateTime nowDateTime = LocalDateTime.now();System.out.println("今天是:" + nowDateTime); System.out.println(nowDateTime.getYear()); System.out.println(nowDateTime.getMonthValue()); System.out.println(nowDateTime.getDayOfMonth()); System.out.println(nowDateTime.getHour()); System.out.println(nowDateTime.getMinute()); System.out.println(nowDateTime.getSecond()); System.out.println(nowDateTime.getNano()); System.out.println("dayofYear:" + nowDateTime.getDayOfYear()); System.out.println(nowDateTime.getDayOfWeek()); System.out.println(nowDateTime.getDayOfWeek().getValue()); System.out.println(nowDateTime.getMonth()); System.out.println(nowDateTime.getMonth().getValue()); LocalDate ld = nowDateTime.toLocalDate();System.out.println(ld); LocalTime lt = nowDateTime.toLocalTime();System.out.println(lt.getHour()); System.out.println(lt.getMinute()); System.out.println(lt.getSecond()); LocalDateTime ldt = LocalDateTime.of(2026 , 9 , 20 , 15 , 23 , 30 );DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss" );String s2 = ldt.format(fmt);
Duration 时间间隔(秒,纳,秒) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 LocalDateTime today = LocalDateTime.now();System.out.println(today); LocalDateTime birthDate = LocalDateTime.of(2000 , 1 , 1 , 0 , 0 , 0 );System.out.println(birthDate); Duration duration = Duration.between(birthDate, today);System.out.println("相差的时间间隔对象:" + duration); System.out.println("============================================" ); System.out.println(duration.toDays()); System.out.println(duration.toHours()); System.out.println(duration.toMinutes()); System.out.println(duration.toMillis()); System.out.println(duration.toNanos());
Period 时间间隔(年,月,日) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 LocalDate today = LocalDate.now();System.out.println(today); LocalDate birthDate = LocalDate.of(2000 , 1 , 1 );System.out.println(birthDate); Period period = Period.between(birthDate, today);System.out.println("相差的时间间隔对象:" + period); System.out.println(period.getYears()); System.out.println(period.getMonths()); System.out.println(period.getDays()); System.out.println(period.toTotalMonths());
ChronoUnit 时间间隔(所有单位) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 LocalDateTime today = LocalDateTime.now();System.out.println(today); LocalDateTime birthDate = LocalDateTime.of(2000 , 1 , 1 ,0 , 0 , 0 );System.out.println(birthDate); System.out.println("相差的年数:" + ChronoUnit.YEARS.between(birthDate, today)); System.out.println("相差的月数:" + ChronoUnit.MONTHS.between(birthDate, today)); System.out.println("相差的周数:" + ChronoUnit.WEEKS.between(birthDate, today)); System.out.println("相差的天数:" + ChronoUnit.DAYS.between(birthDate, today)); System.out.println("相差的时数:" + ChronoUnit.HOURS.between(birthDate, today)); System.out.println("相差的分数:" + ChronoUnit.MINUTES.between(birthDate, today)); System.out.println("相差的秒数:" + ChronoUnit.SECONDS.between(birthDate, today)); System.out.println("相差的毫秒数:" + ChronoUnit.MILLIS.between(birthDate, today)); System.out.println("相差的微秒数:" + ChronoUnit.MICROS.between(birthDate, today)); System.out.println("相差的纳秒数:" + ChronoUnit.NANOS.between(birthDate, today)); System.out.println("相差的半天数:" + ChronoUnit.HALF_DAYS.between(birthDate, today)); System.out.println("相差的十年数:" + ChronoUnit.DECADES.between(birthDate, today)); System.out.println("相差的世纪(百年)数:" + ChronoUnit.CENTURIES.between(birthDate, today)); System.out.println("相差的千年数:" + ChronoUnit.MILLENNIA.between(birthDate, today)); System.out.println("相差的纪元数:" + ChronoUnit.ERAS.between(birthDate, today));
包装类
方法名
说明
public Integer(int value)
根据 int 值创建 Integer 对象(过时)
public Integer(String s)
根据 String 值创建 Integer 对象(过时)
public static Integer valueOf(int i)
返回表示指定的 int 值的 Integer 实例
public static Integer valueOf(String s)
返回保存指定String值的 Integer 对象
public static string toBinarystring(int i)
得到二进制
public static string toOctalstring(int i)
得到八进制
public static string toHexstring(int i)
得到十六进制
public static int parseInt(string s)
将字符串类型的整数转成int类型的整数
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 36 37 38 39 40 41 42 43 44 45 46 47 48 Integer i1 = new Integer (100 );Integer i2 = new Integer ("100" );Integer i3 = Integer.valueOf(100 );Integer i4 = Integer.valueOf("100" );int x = i.intValue();Integer i = 4 ;i = i + 5 ; int number = 100 ;String s1 = number + "" ;System.out.println(s1); String s2 = String.valueOf(number);System.out.println(s2); String s = "100" ;Integer i = Integer.valueOf(s);int x = i.intValue();System.out.println(x); int y = Integer.parseInt(s);System.out.println(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 25 26 27 28 29 30 31 32 33 34 int [] arr = {7 , 23 , 79 , 81 , 103 , 127 , 131 , 147 };System.out.println(binarySearch(arr, 150 )); public static int binarySearch (int [] arr, int number) { int min = 0 ; int max = arr.length - 1 ; while (true ){ if (min > max){ return -1 ; } int mid = (min + max) / 2 ; if (arr[mid] > number){ max = mid - 1 ; }else if (arr[mid] < number){ min = mid + 1 ; }else { return mid; } } }
插入排序 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 36 37 38 int [] arr = {3 , 44 , 38 , 5 , 47 , 15 , 36 , 26 , 27 , 2 , 46 , 4 , 19 , 50 , 48 };int startIndex = -1 ;for (int i = 0 ; i < arr.length; i++) { if (arr[i] > arr[i + 1 ]){ startIndex = i + 1 ; break ; } } for (int i = startIndex; i < arr.length; i++) { int j = i; while (j > 0 && arr[j] < arr[j - 1 ]){ int temp = arr[j]; arr[j] = arr[j - 1 ]; arr[j - 1 ] = temp; j--; } } for (int i = startIndex; i < arr.length; i++) { int num = arr[i]; int j = i - 1 ; while (j >= 0 && num < arr[j]) { arr[j + 1 ] = arr[j]; j--; } arr[j + 1 ] = num; }
快速排序 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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 public static void quickSort (int [] arr, int i, int j) { int start = i; int end = j; if (start > end){ return ; } int baseNumber = arr[i]; while (start != end){ while (true ){ if (end <= start || arr[end] < baseNumber){ break ; } end--; } System.out.println(end); while (true ){ if (end <= start || arr[start] > baseNumber){ break ; } start++; } int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; } int temp = arr[i]; arr[i] = arr[start]; arr[start] = temp; quickSort(arr,i,start - 1 ); quickSort(arr,start + 1 ,j); }
枚举类 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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 public class EnumDemo { enum Color { RED, GREEN, BLUE; } enum Status { SUCCESS(200 , "成功" ), NOT_FOUND(404 , "未找到" ), ERROR(500 , "服务器错误" ); private final int code; private final String msg; Status(int code, String msg) { this .code = code; this .msg = msg; } public int getCode () { return code; } public String getMsg () { return msg; } public static Status fromCode (int code) { for (Status s : values()) { if (s.code == code) return s; } throw new IllegalArgumentException ("未知 code: " + code); } } interface Describable { String desc () ; } enum Level implements Describable { LOW { @Override public String desc () { return "低" ; } }, HIGH { @Override public String desc () { return "高" ; } }; } public static void main (String[] args) { Color c = Color.RED; System.out.println(c.name()); System.out.println(c.ordinal()); for (Color color : Color.values()) { System.out.println(color); } Color c2 = Color.valueOf("GREEN" ); switch (c) { case RED -> System.out.println("红色" ); case GREEN -> System.out.println("绿色" ); case BLUE -> System.out.println("蓝色" ); } Status s = Status.fromCode(404 ); System.out.println(s.getCode() + " " + s.getMsg()); System.out.println(Level.HIGH.desc()); } }
Arrays 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 36 37 38 39 40 41 Arrays.toString(arr); Arrays.deepToString(mat); Arrays.sort(arr); Arrays.sort(arr, from, to); Arrays.sort(arr, Comparator.reverseOrder()); Arrays.sort(a, new Comparator <Integer>() { @Override public int compare (Integer o1, Integer o2) { return o2.compareTo(o1); } }); Arrays.parallelSort(arr); int i = Arrays.binarySearch(arr, key); int i = Arrays.binarySearch(arr, from, to, key); Arrays.fill(arr, val); Arrays.fill(arr, from, to, val); int [] b = Arrays.copyOf(arr, newLen); int [] c = Arrays.copyOfRange(arr, from, to); boolean ok = Arrays.equals(a, b); boolean ok = Arrays.deepEquals(m1, m2); int h = Arrays.hashCode(arr); int h = Arrays.deepHashCode(mat); int p = Arrays.mismatch(a, b); int r = Arrays.compare(a, b); List<Integer> list = Arrays.asList(1 , 2 , 3 ); Stream<Integer> st = Arrays.stream(arr); Arrays.setAll(arr, i -> i * i); Arrays.parallelSetAll(arr, i -> f(i));
lambda表达式 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 @FunctionalInterface interface IntCalc { int apply (int a, int b) ; default void log () {} boolean equals (Object o) ; } IntCalc add = (a, b) -> a + b; list.sort((x, y) -> y - x); Arrays.sort(a, (Integer o1, Integer o2) -> { return o1-o2; }); Arrays.sort(a, (o1, o2) -> o1-o2); Collection<String> coll = new ArrayList <>(); coll.add("zhangsan" ); coll.add("lisi" ); coll.forEach(s -> System.out.println(s));