# java11特性

## 语法层次

### 局部变量类型推断升级

> 局部变量类型推断是java10开始新增的新特性,java11中对局部变量推断进行了升级,在var支持添加注解的语法格式,JAVA10中是无法实现的,在JAVA11中加入了这样的语

lambda表达式中,注解修饰变量的时候,变量的数据类型必须要写,不能省略,像下面这种写法就是错误的

```java
Consumer<String> con =(@Deprecated  t) -> System.out.println(t.toLowerCase());
```

这个时候就必须要为小括号中的参数添加数据类型,应该这样写

```java
Consumer<String> con =(@Deprecated String t) -> System.out.println(t.toLowerCase());
```

java11中,lambda表达式中的参数数据类型可以使用var,但是不能不写

```java
Consumer<String> con =(@Deprecated var t) -> System.out.println(t.toLowerCase());
```

## API层次

### String新增API

| API        | 描述                                        |
| ---------- | ----------------------------------------- |
| 判断字符串是否为空白 | `str.isBlank()`                           |
| 去除字符串首尾空白  | `str.strip()`                             |
| 去除字符串尾部空白  | `str.stripTrailin()`                      |
| 去除字符串首部空白  | `str.stripLeading()`                      |
| 重复字符串      | `str.repeat(2)`，如果str为`ab`，则方法执行结果为`abab` |
| 行数统计       | `str.lines().count()`                     |

### Optional新增API

| 新增方法                                                                | 描述                                            | 新增版本  |
| ------------------------------------------------------------------- | --------------------------------------------- | ----- |
| `boolean isEmpty()`                                                 | 判断value是否为空                                   | JDK11 |
| `T orElseThrow()`                                                   | value非空,返回value,否则抛出NoSuchElementExpception   | JDK10 |
| `ifPresentOrElse(Consumer<? super T> action,Runnable emptyAction)`  | value非空,执行参数1功能,如果value为空,执行参数2功能             | JDK9  |
| `Optional<T> or(Supplier<? extends Optional<? extends T> supplier)` | value非空,返回对应的Optional,value为空,返回形参封装的Optional | JDK9  |
| `Stream<T> stream()`                                                | value非空,返回一个仅包含此value的Steam,否则,返回一个空的Stream   | JDK9  |

```java
Optional<String> optional =Optional.empty();
//JDK8 判断value是否存在
System.out.println(optional.isPresent()); // false
//JDK11 判断value是否为空
System.out.println(optional.isEmpty()); // true

//JDK10 返回value,如果为null则直接抛出 NoSuchElementExpception
Optional<String> optional2 = Optional.of("element1");
String value = optional2.orElseThrow();
System.out.println(value);

//JDK9  value非空,执行参数1功能,如果value为空,执行参数2功能
Optional<String> optional3 =Optional.empty();// Optional.of("element1");
optional.ifPresentOrElse((v)-> System.out.println("value为"+v),()-> System.out.println("value为null"));

// JDK9 value非空,返回对应的Optional,value为空,返回形参封装的Optional
Optional<String> optional4 =Optional.empty();// Optional.of("element1");
Optional<String> optional5 = optional4.or(() -> Optional.of("element2"));
System.out.println(optional5);

// JDK9 value非空,返回一个仅包含此value的Steam,否则,返回一个空的Stream
Optional<String> optional6 =Optional.of("element3");//Optional.empty();
Stream<String> stream = optional6.stream();
stream.forEach(System.out::println); 
```

### HttpClient

是新的http请求客户端工具：

```java
//HttpClient 替换原有的HttpUrlConnection  同步方式
HttpClient client =HttpClient.newHttpClient();
HttpRequest request =HttpRequest.newBuilder(URI.create("http://127.0.0.1:8080/demo")).build();
HttpResponse.BodyHandler<String> respnoseBodyHandler= HttpResponse.BodyHandlers.ofString();
HttpResponse<String> response =client.send(request,respnoseBodyHandler);
String body = response.body();
System.out.println(body);
```

## 其他变化

### 更简化的编译运行

```shell
# 编译运行
javac Test.java
java Test

# Java11支持直接使用java命令直接编译运行
java Test.java
```

注意：

1. 如果Test.java类中有多个main方法，则会使用第一个main方法
2. 简化编译只能编译引用当前文件中的类，以及JDK中的相关类，不能引用其他类（比如同包下的某个Student.java中的类）

### ZGC

### 废弃 Nashorn


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://yangsx95.gitbook.io/notes/programming-language/java/java-te-xing/java11-te-xing.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
