A small knot
Many novice Java junior partner often consult:
- In the end of the installation which version of the JDK is better?
- Java 8 in the end also enough to use?
- Java 11 exactly what improvements?
- Is not the more the better new version of Java?
- ……
So, in fact, the official website now to have a version of Java 13, and provides a download.
But currently on the market mainstream stable version of course, you have to belong to Java 8 and the Java 11 , and now most of the company's production environment or Java 8
the majority. So if from the perspective of self-study, I think these two versions are OK, some other intermediate such Java 9
, Java 10
these non-stable version would not have considered.
Java11 vs Java8
Java 11 with respect to Java 8 is indeed a part of evolution, in addition to many internal upgrades (such as lower cost and delay of GC, TLS1.3 blessing, etc.) than for novice users who are also some aspects of language use evolution.
Recently, I just try to use a little upgrade on their own personal little project Java 11
(project company we are not daring to move, afraid to ask, had to move their personal items), this article written from the perspective of the actual code to roughly my personal experience use Java 11
after a relatively Java 8
felt by some of the more profound evolution, say the official documentation is very clear:https://docs.oracle.com/en/java/javase/11/
I have this experiment installed Java 11
version is 11.0.6
:
Below to test some of the new features proven fact, not
Java 11
only the introduction, in fact, a lotJava 9
andJava 10
have been introduced when, but toJava 11
the stable version before settling down.
Variable type inference
The new version of Java introduces a new type keyword var
, use var
variables to define the need to write specific types, according to the compiler can =
automatically infer the type of the variable actual assignment of the right:
1, the general local variables
var name = "codesheep"; // 自动推断name为String类型
System.out.println(name);
how about it? Is there is a similar use of JavaScript in a weakly typed language this illusion?
2, for use in the loop
var upList1 = List.of( "刘能", "赵四", "谢广坤" );
var upList2 = List.of( "永强", "玉田", "刘英" );
var upList3 = List.of( "谢飞机", "兰妮", "兰娜" );
var upListAll = List.of( upList1, upList2, upList3 );
for( var i : upListAll ) { // 用var接受局部变量的确非常简洁!
for( var j : i ) {
System.out.println(j);
}
}
This place can be seen with the var
advantage of local variables defined, and if this example the collection element type is more complex, is similar to List<List<String>>
this type of nesting, then var
the definition is very clear and concise!
3, of course, some cases can not be used
var
Once the type of variable assignment and re-assignment of different types is not enough, for example:
var name = "codesheep";
name = 666; // 此时编译会提示不兼容的类型
Definition of var
the type of uninitialized variables is not enough, for example:
var foo; // 此时编译会提示无法推断类型
foo = "Foo";
In addition, like type 成员变量类型
, 方法入参类型
, 返回值类型
and the like can not be used var
, for example:
public class Test {
private var name; // 会提示不允许使用var
public void setName( var name ) { // 会提示不允许使用var
this.name = name;
}
public var getName() { // 会提示不允许使用var
return name;
}
}
HTTP Client official blessing
Yes!
Now JDK
official comes on HTTP Client
, and is located java.net.http
under the package, supports sending synchronous, asynchronous HTTP
requests, so that, before we used the HTTP request from the client such as: OKHttp
, HttpClient
which can now step down!
Sends a synchronization request:
var request = HttpRequest.newBuilder()
.uri( URI.create("https://www.codesheep.cn") )
.GET()
.build();
// 同步请求方式,拿到结果前会阻塞当前线程
var httpResponse = HttpClient.newHttpClient()
.send( request, HttpResponse.BodyHandlers.ofString());
System.out.println( httpResponse.body() ); // 打印获取到的网页内容
Asynchronous request is sent:
CompletableFuture<String> future = HttpClient.newHttpClient().
sendAsync( request, HttpResponse.BodyHandlers.ofString() )
.thenApply( HttpResponse::body );
System.out.println("我先继续干点别的事情...");
System.out.println( future.get() ); // 打印获取到的网页内容
Of course, you can also customize the request header, such as carrying JWT Token
authority to request information such as:
var requestWithAuth = HttpRequest.newBuilder()
.uri( URI.create("http://www.xxxxxx.com/sth") )
.header("Authorization", "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxNTIwNTE2MTE5NiIsImNyZWF0ZWQiOjE1ODMzMTA2ODk0MzYsImV4cCI6MTU4MzM5NzA4OSwidXNlcmlkIjoxMDAwNH0.OE9R5PxxsvtVJZn8ne-ksTb2aXXi7ipzuW9kbCiQ0uNoW0fJJr_wckLFmgDzxmBs3IdzIhWDAtaSIvmTshK_RQ")
.GET()
.build();
var response = HttpClient.newHttpClient()
.send( requestWithAuth, HttpResponse.BodyHandlers.ofString() );
System.out.println( response.body() ); // 打印获取到的接口返回内容
String handling enhancements
The new string String
type such as an increase: isBlank()
, strip()
, repeat()
and the like to facilitate the string processing method
String myName = " codesheep ";
System.out.println( " ".isBlank() ); // 打印:true
System.out.println( " ".isEmpty() ); // 打印:false
System.out.println( myName.strip() ); // 打印codesheep,前后空格均移除
System.out.println( myName.stripLeading() ); // 打印codesheep ,仅头部空格移除
System.out.println( myName.stripTrailing() ); // 打印 codesheep,仅尾部空格移除
System.out.println( myName.repeat(2) ); // 打印 codesheep codesheep
Enhanced collection
Mainly to increase such of()
and copyOf()
methods for more convenient to create and copy collection types
var upList = List.of( "刘能", "赵四", "谢广坤" );
var upListCopy = List.copyOf( upList );
System.out.println(upList); // 打印 [刘能, 赵四, 谢广坤]
System.out.println(upListCopy); // 打印 [刘能, 赵四, 谢广坤]
var upSet = Set.of("刘能","赵四");
var upSetCopy = Set.copyOf( upSet );
System.out.println(upSet); // 打印 [赵四, 刘能]
System.out.println(upSetCopy); // 打印 [赵四, 刘能]
var upMap = Map.of("刘能","58岁","赵四","59岁");
var upMapCopy = Map.copyOf( upMap );
System.out.println(upMap); // 打印 {刘能=58岁, 赵四=59岁}
System.out.println(upMapCopy); // 打印 {刘能=58岁, 赵四=59岁}
Functional Programming enhancements
What impressed me most is Stream
the stream, such as increased takeWhile()
and dropWhile()
the cut-off settlement method:
var upList = List.of( "刘能", "赵四", "谢广坤" );
// 从集合中依次删除满足条件的元素,直到不满足条件为止
var upListSub1 = upList.stream()
.dropWhile( item -> item.equals("刘能") )
.collect( Collectors.toList() );
System.out.println(upListSub1); // 打印 [赵四, 谢广坤]
// 从集合中依次获取满足条件的元素,知道不满足条件为止
var upListSub2 = upList.stream()
.takeWhile( item -> item.equals("刘能") )
.collect( Collectors.toList() );
System.out.println( upListSub2 ); // 打印 [刘能]
Enhanced file read and write
1, Files Class enhancement
We can direct your mind and heart before the contents of the file to read String
and String
features written back to the file finally supported, by Files
the static method of the class writeString()
and readString()
complete:
Path path = Paths.get("/Users/CodeSheep/test.txt");
String content = Files.readString(path, StandardCharsets.UTF_8);
System.out.println(content);
Files.writeString( path, "王老七", StandardCharsets.UTF_8 );
2, InputStream enhanced
InputStream
Increased by a transferTo()
method, the data directly thrown into the OutputStream
go:
InputStream inputStream = new FileInputStream( "/Users/CodeSheep/test.txt" );
OutputStream outputStream = new FileOutputStream( "/Users/CodeSheep/test2.txt" );
inputStream.transferTo( outputStream );
Support source files directly run (666!)
For example, I wrote a simple Hello World
program:
public class Hello {
public static void main( String[] args ) {
System.out.println("hello world");
}
}
And save it as hello.java
a file, this time directly with the java
command to run the Java source files directly eliminating the previous javac
process to compile the source file:
java hello.java
how about it? Is not the source files and run python bit like? The amount of information a bit big, we can make it on their own brain
summary
Java 11 does have a lot to improve, but then again, for beginners Java 8, no need to deliberately novelty, stability is the most important!