语法糖

语法糖(Syntactic sugar)是由英国计算机科学家彼得·兰丁发明的一个术语,指计算机语言中添加的某种语法,这种语法对语言的功能没有影响,但是更方便程序员使用。语法糖让程序更加简洁,有更高的可读性。

ForEach

for(type element: array){    System.out.println(element);}

批注 2019-10-20 163312

枚举

public enum Size{    SMALL,MEDIUM,LARGE;}

接口返回值不允许使用枚举类型的原因是如果类库没有及时升级,在反序列化的时候当根据序列化数据序列相应枚举的话很可能找不到相应枚举。从而抛异常

不定项参数

public void method(String a,String...b){ }

为什么要可变参数?

变长参数适应了不定参数个数的情况,避免了手动构造数组,提高语言的简洁性和代码的灵活性

当可变参数与方法重载出现时,就有些令人混乱,但整体方法参数匹配流程是这样的:

阶段1: 不自动装箱拆箱,不匹配变长参数阶段2: 自动装箱拆箱,不匹配可变参数阶段3: 允许匹配变长参数

静态导入

import static org.junit.Assert.*;

自动装拆箱

Integer a = 1;

多异常并列

try{    //...}catch(Exception1 | Exception2 e){    //...}

数值新特性

int a = 0b11100111; // 可直接使用二进制int b = 9999_99999; // 可使用下划线分割

接口方法

default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)            throws Exception {    return true;}

批注 2019-10-20 194253

接口静态方法

public interface Runnable {    static void run(){        System.out.println("!111");    }}

接口私有方法

public interface Runnable {    static void run(){        say();    }        private static void say(){        System.out.println("say");    }        }

try-with-resource

try(FileOutputStream fos = new FileOutputStream("")){ //JDK7            } catch (IOException e) {    e.printStackTrace();}
        FileOutputStream fos = new FileOutputStream(""); // JDK9        try(fos){        } catch (IOException e) {            e.printStackTrace();        }

var

var a = 1;
var obj = new Object(){    public void print(){        System.out.println("print");    }};obj.print();

批注 2019-10-22 204413

switch表达式

int ret = switch (a){    case 1-> 100;    case 2 -> 200;    default -> -1;};

文本块

String template =                """                welcome,                hello "${name}"                """;System.out.print(template);

Records

record Person(String firstname, String lastname) {    Person {        if (firstname == null || lastname == null) {            throw new IllegalArgumentException("firstname or lastname cannot be null");        }    }}Person person = new Person("c", "xk");person.firstname();person.lastname();

instanceof模式匹配

Object obj = "cxk";if (obj instanceof String s) {    System.out.println(s);}if (obj instanceof String s && s.length() > 2) {    System.out.println(s);}

密封类

密封类允许你控制类的继承体系结构

abstract sealed class Animal permits Dog, Cat {}final class Dog extends Animal{}final class Cat extends Animal{}