Java基础
程序入口
public class HelloWorld {
public static void main(String[] args) {//入口
System.out.println("Hello World"); // 输出 Hello World
}
}
数据类型
不能表示金钱
类型 | 长度 | 范围 |
---|---|---|
byte | 8 | [-128,127] |
short | 16 | [-32768,32767] |
int | 32 | [-2,147,483,648,2,147,483,647] |
long | 64 | [-9,223,372,036,854,775,808,9,223,372,036,854,775,807] |
float | 32 | 10^38 |
double | 64 | 10^308 |
boolean | ||
char | 16 | [0,65535] |
Scanner输入
1、概念
源码:
* A simple text scanner which can parse primitive types and strings using
* regular expressions.
*
* <p>A <code>Scanner</code> breaks its input into tokens using a
* delimiter pattern, which by default matches whitespace. The resulting
* tokens may then be converted into values of different types using the
* various <tt>next</tt> methods.
一个简单的文本扫描程序,可以使用正则表达式解析基元类型和字符串。Scanner使用分隔符模式将其输入分解为标记,默认情况下,分隔符模式与空白相匹配。然后,可以使用各种<tt>next<tt>方法将生成的令牌转换为不同类型的值。
-
输出Int类型
Scanner scanner = new Scanner(System.in);//System.in用来获得控制台输入 int i = scanner.nextInt(); System.out.println(i);
-
输出字符,其他类型同理
String input = "1 fish 2 fish red fish blue fish"; Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*"); System.out.println(s.nextInt()); System.out.println(s.nextInt()); System.out.println(s.next()); System.out.println(s.next()); s.close();//关闭扫描器
按照得到fish分隔扫描字符串
* 1 * 2 * red * blue
字符串常用
判断是否相同
contentEqual函数
String s1="My name is Lilei";
String s2="My name is Limei";
boolean b = s1.contentEquals(s2);
System.out.println(b);
equalsIgnoreCase,compareToIgnoreCase函数忽略某种条件进行字符串判断和比较,regionMatches判断两个某区域是否匹配
判断字符串开头,结尾endsWith同理
String s1="My name is Lilei";
String s2="My name is Limei";
boolean b1 = s1.startsWith("My");//默认从头开始比较,偏移为0
boolean b2= s1.startsWith("name", 3);//偏移为3
System.out.println(b1);
System.out.println(b2);
返回此字符串中指定字符第一次出现的索引,最后一次出现lastIndexOf同理
String s1="My name is Lilei";
String s2="My name is Limei";
System.out.println(s2.indexOf("is"));//默认从index为0开始
System.out.println(s2.indexOf("i",9));//从index为9开始算
获得部分字符串
String s1="My name is Lilei";
String s2="My name is Limei";
System.out.println(s2.substring(0,2));
拼接字符串
String s1="My name is Lilei";
String s2="My name is Limei";
System.out.println(s1.concat(s2));
System.out.println(s1 + s2);
String message = String.join("-", "Java", "is", "cool");
System.out.println(message);
替换字符串
String s1="My name is Lilei";
String s2="My name is Limei";
System.out.println(s1.replace("My","Your"));
匹配/包含字符串
String s1="My name is Lilei";
String s2="My name is Limei";
System.out.println(s1.matches("My(.*)"));//matches参数为正则表达式
System.out.println(s1.contains("is"));
分割字符串
String s1="My name is Lilei";
String s2="My name is Limei";
for (String s : s1.split(" ",2)) {//按空格分割成两个字符串
System.out.println(s);
}
}
大小写转换
String s1="My name is Lilei";
String s2="My name is Limei";
System.out.println(s1.toLowerCase());
System.out.println(s2.toUpperCase());
去除前后空格
String s1=" My name is Lilei ";
String s2="My name is Limei";
System.out.println(s1.trim());
字符串转数组
String s1="My name is Lilei";
String s2="My name is Limei";
char[] chars = s1.toCharArray();
System.out.println(chars[1]);
字符串格式化
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss.SSS");
System.out.println(simpleDateFormat.format(new Date()));
类型转换
int i=1;
System.out.println(String.valueOf(i));
System.out.println(Integer.toString(i));
随机数
Random r = new Random(2);//随机种子不变,随机数不变
System.out.println(r.nextInt(5));//输出0~4的随机整数
数组
静态初始化、动态初始化、遍历
int[] ints = {1, 2, 3};
long[] longs = new long[10];
for (int i = 0; i <9 ; i++) {
longs[i] = ints[i];
}
this关键字
String name ="lilei";
public void getName(String name){
System.out.println(name);//输出局部name,就近原则
System.out.println(this.name);//输出成员变量name
this.getMethod();//输出成员方法
}
public void getMethod(){
System.out.println("method");
System.out.println(this);//输出对象地址
}
构造器
1、初始化对象
2、构建创造对象时所调用的方法
3、每创建一次对象就执行一次构造方法
public class User {
public String name;
public Integer age;
User() {
System.out.println("User无参构造方法");
this.name = "lilei";
this.age=18;
}
User(String name,int age) {
System.out.println("User有参构造方法");
this.name = "lilei";
this.age=18;
}
}
StringBuilder
一个可变的字符序列。 在可能的情况下,建议使用这个类别优先于StringBuffer
因为它在大多数实施中将更快。 一个StringBuilder
的主要操作是append
和insert
方法,append
方法总是在构建器的末尾添加这些字符; insert
方法将字符添加到指定点。
StringBuilder sb = new StringBuilder("99");
sb.append("111");
sb.delete(1,2);
sb.insert(2,3);
sb.reverse();
System.out.println(sb);
个位数倒序
StringBuilder sb = new StringBuilder();
int[] i = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
for (int p : i) {
sb.append(p+" ");
}
sb.reverse();//倒排
String s = sb.toString().trim();//去空格
String[] split = s.split(" ");
for (int i1 = 0; i1 < split.length; i1++) {
i[i1]=Integer.valueOf(split[i1]);
}
for (int i1 : i) {
System.out.println(i1);
}
匿名内部类
参数为接口类型的方法,调用该方法时使用匿名内部类实现接口对象
public class Test {
public static void main(String[] args) {
testInter(new Inter() {
@Override
public void say() {
System.out.println("111");
}
});
}
public static void testInter(Inter inter){
inter.say();
}
}
interface Inter {
void say();
}
toString/equals方法
默认toString返回的是全类名+@+对象内存地址通过哈希算法得到的十六进制数,通过重写toString方法可以提高对象的辨识度
//toString源码
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
class B{
int age;
String name;
@Override
public String toString() {
return "B{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}
object与String的equals方法不一样object.equals默认比较地址,String.equals默认比较数值
Object o1 = new Object();
Object o2= new Object();
String s1="1";
String s2 = "1";
System.out.println(o1==o2);
System.out.println(o1.equals(o2));
System.out.println(s1==s2);
System.out.println(s1.equals(s2));
BigDecimal
解决小数运算不精确问题
初始化
BigDecimal b1 = new BigDecimal(0.3);//不推荐,不精确
BigDecimal b2 = BigDecimal.valueOf(0.3);
BigDecimal b3 = new BigDecimal("0.3");
BigDecimal b4 = BigDecimal.valueOf(0.3);
System.out.println(b1.equals(b3));
System.out.println(b2.equals(b4));
System.out.println(b2.equals(b3));
Array
int[] a1 = {1, 2, 3, 4};
Integer[] a2 = {1, 2, 5, 4};
System.out.println(Arrays.binarySearch(a1, 4));
Arrays.sort(a2,1,4);//升序
Arrays.sort(a2,new Comparator<Integer>() {//降序
@Override
public int compare(Integer o1, Integer o2) {
return o2.intValue() - o1.intValue();
}
});
System.out.println(Arrays.toString(a2));
}
日历时间
1、日历类
LocalDate:年月日
LocalTime:时分秒
LocalDateTime:年月日时分面
System.out.println(LocalDateTime.now());
System.out.println(LocalDate.now());
System.out.println(LocalTime.now());
System.out.println(LocalDateTime.of(2023, 12, 1, 11, 2, 5));//of方法直接修改全部时间
System.out.println(LocalDate.of(2023, 12, 1));
System.out.println(LocalTime.of(11, 2, 5));
LocalDateTime now = LocalDateTime.now();
System.out.println(now.getMonthValue());
处理时间
1、修改用with,只能修改一部分 2、加时间用plus 3、减时间用minus 4、判断用is
LocalDateTime now = LocalDateTime.now();
System.out.println(now.plusDays(1));
System.out.println(now.minusHours(2));
System.out.println(now.withSecond(3));
LocalDateTime t1 = LocalDateTime.of(2023, 12, 1, 11, 2, 5);
System.out.println(now.isEqual(t1));
System.out.println(now.isAfter(t1));
System.out.println(now.isBefore(t1));
2、日期格式化类
DateTimeFormatter:时间格式化和解析,类似字符串格式化
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-d");
System.out.println(formatter.format(LocalDate.now()));
DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy/M/d");
String s="2023/12/1";
System.out.println(LocalDate.parse(s, formatter1));
3、时间类
Instant:时间戳
ZoneId:时区
ZoneDateTime:带时区的时间
//获取java中所有时区
Set<String> ids = ZoneId.getAvailableZoneIds();
System.out.println(ids);
System.out.println(ids.size());
//获取系统默认时区
ZoneId zoneId = ZoneId.systemDefault();
System.out.println(zoneId);
//获取指定时区
ZoneId of = ZoneId.of("Africa/Nairobi");
System.out.println(of);
//带时区的时间
System.out.println(Instant.now().atZone(of));
4、工具类
Period:时间间隔(年,月,日)
Duration:时间间隔(时,分,秒,纳秒)
ChronoUnit:时间间隔(所有单位),主要用这个
LocalDateTime now = LocalDateTime.now();
LocalDateTime of = LocalDateTime.of(2023, 2, 4,12,42,33);
System.out.println(ChronoUnit.YEARS.between(of, now));
System.out.println(ChronoUnit.MONTHS.between(of, now));
异常
非运行时异常抛出或捕获,捕获异常程序不会停止,抛出异常会停止。
子类重写父类方法,不能抛出父类没有的或比父类更大的异常。
集合
包含xxList、xxSet、xxMap等
Collection常用方法add clear isEmpty size,其中 remove contain底层依赖于equals方法,要注意重写类的equals方法
遍历
1、迭代器
2、增强for循环
3、foreach
ArrayList<String> list = new ArrayList<>();
list.add("zhangsan");
list.add("wangwu");
list.add("wanglei");
//1、用迭代器
Iterator<String> it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
//2、增强for循环
for (String s : list) {
System.out.println(s);
}
//3、foreach,使用内部类
list.forEach(new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s); }
});
//3、foreach,使用lambda函数
list.forEach((s)->{
System.out.println(s);
});
方法
list按索引进行add、remove、set、get
TreeSet特点:排序、去重
Collection方法:addAll、shuffle、binarySearch、max、min、swap
Map方法:put 、remove、clear、containKey、containValue、isEmpty、size
注意:排序重写Comparable接口,唯一性重写hashCode和equals方法
Stream流
流式处理数据,后续Flink会详细写
体验
ArrayList<String> list = new ArrayList<>();
list.add("李四");
list.add("李世民");
list.add("王五");
list.add("赵六");
list.stream().filter(s -> s.startsWith("李")).filter(s -> s.length() ==2).forEach(System.out::println);
获取流
双列获取stream流
HashMap<String, String> map = new HashMap<>();
map.put("zhangsan","101");
map.put("lisi","23");
map.put("wangwu","33");
Set<Map.Entry<String, String>> set = map.entrySet();
set.stream().forEach(s->System.out.println(s) );
数组获取流
int[] a={1,2,3};
IntStream stream = Arrays.stream(a);
零散数据
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4);
处理流
方法:filter、limit、skip、distinct去重(依赖hashCode和equals方法)、concat合并,流被消费就不能再次使用
输出流
方法:forEach、count
收集流
Stream操作不会改变原始数据,收集流的输出用collect方法:Collectors.toList(),.toSet(),.toMap()
List<String> l = list.stream().filter(s -> s.startsWith("李")).filter(s -> s.length() == 2).collect(Collectors.toList());
list转map使用Collectors.toMap()方法
ArrayList<String> list = new ArrayList<>();
list.add("zhangsan,101");
list.add("lisi,23");
list.add("wangwu,33");
Map<String, Integer> collect = list.stream().filter(s -> Integer.parseInt(s.split(",")[1]) >= 23).collect(Collectors.toMap(new Function<String, String>() {
@Override
public String apply(String s) {
return s.split(",")[0];
}
}, new Function<String, Integer>() {
@Override
public Integer apply(String s) {
return Integer.parseInt(s.split(",")[1]);
}
}));
System.out.println(collect);
File
1、判断
isXXX,exist
2、获取
getXXX,length
3、创建和构造
File file1 = new File("E:\\learn\\JavaBasic\\testFile1.txt");
file1.createNewFile();
File file2 = new File("E:\\learn\\JavaBasic");
System.out.println(file2.exists());
File file3 = new File("E:\\", "learn\\JavaBasic");
System.out.println(file3.exists());
File file4 = new File(new File("E:\\"), "learn\\JavaBasic");
System.out.println(file4.exists());
File file = new File("");
System.out.println(file.getAbsolutePath());
System.out.println(file1.isFile());
File file5 = new File("E:\\learn\\JavaBasic\\testFile1\\aa");
file5.mkdirs();
4、删除
delete
5、遍历listFiles
File file = new File("E:\\learn\\JavaBasic");
File[] files = file.listFiles();
Arrays.stream(files).forEach(System.out::println);
Arrays.stream(files).filter((file1)->{
return file1.getName().endsWith("txt");
}).forEach(System.out:: println);
IO流
1、文件输出流FileOutputStream
FileOutputStream f = new FileOutputStream("E:\\learn\\JavaBasic\\1.txt");
f.write(88);
byte[] b={45,77,44};
f.write(b);
f.write("haha".getBytes());
f.close();
2、字节输入流FileInputStream
FileInputStream i = new FileInputStream("E:\\learn\\JavaBasic\\1.txt");
System.out.println(i.read());
byte[] b=new byte[3];
i.read(b);
System.out.println(Arrays.toString(b));
3、文件拷贝
FileInputStream i = new FileInputStream("E:\\learn\\JavaBasic\\20210309205430.png");
FileOutputStream f = new FileOutputStream("E:\\learn\\20210309205430.png");
byte[] b=new byte[1024];
while (i.read(b) > 0) {
f.write(b, 0, 1024);
}
i.close();
f.close();
4、字节缓冲流,提高读写效率
(1)普通拷贝,耗时48毫秒
long start = System.currentTimeMillis();
FileInputStream i = new FileInputStream("E:\\learn\\JavaBasic\\h_(002).psd");
FileOutputStream f = new FileOutputStream("E:\\learn\\h_(002).psd");
byte[] b=new byte[1024];
while (i.read(b) > 0) {
f.write(b, 0, 1024);
}
i.close();
f.close();
System.out.println(System.currentTimeMillis()-start);
(2)缓冲流拷贝,耗时13毫秒
long start = System.currentTimeMillis();
FileInputStream i = new FileInputStream("E:\\learn\\JavaBasic\\h_(002).psd");
FileOutputStream f = new FileOutputStream("E:\\learn\\h_(002).psd");
BufferedInputStream bi = new BufferedInputStream(i);
BufferedOutputStream bo = new BufferedOutputStream(f);
byte[] b=new byte[1024];
while (bi.read(b) > 0) {
bo.write(b, 0, 1024);
}
i.close();
f.close();
System.out.println(System.currentTimeMillis()-start);
5、字符流
用于读取纯文本文件,解决乱码
FileReader fr = new FileReader("E:\\learn\\JavaBasic\\1.txt");
int i ;
while (( i = fr.read())!=-1) {
System.out.print((char) (i));
}
fr.close();
FileWriter fw = new FileWriter("E:\\learn\\JavaBasic\\1.txt");
fw.write("1");
fw.write(new char[] {
'a','b','c'
});
fw.write("haha");
fw.flush();//输出字符流
fw.write("aaa");
fw.close();
6、字符编码
GBK:每个中文占2个字节,英文字符占1个字节
Unicode:每个中文占3个字节,ASCII占一个字节(UTF-8)
String s="哈喽";
byte[] bytes = s.getBytes();
byte[] bytes1 = s.getBytes("GBK");
System.out.println(Arrays.toString(bytes));
System.out.println(Arrays.toString(bytes1));
System.out.println(new String(bytes));
System.out.println(new String(bytes1, "GBK"));