Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the new Java feature

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to use the new Java feature". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use the new Java feature".

1 Try-with-resource statement

When using try-catch blocks to handle exceptions, you usually need to add cleanup code through finally blocks. With try with resource syntax now, developers don't have to worry about resource release.

We can add a resource in try parentheses to close or clean up the resource after the try-catch block is executed

Old grammar

Scanner scanner = null; try {scanner = new Scanner (new File ("foo.txt")); while (scanner.hasNext ()) {System.out.println (scanner.nextLine ());}} catch (FileNotFoundException e) {e.printStackTrace ();} finally {if (scanner! = null) scanner.close ();}

New grammar

Try (Scanner scanner = new Scanner (new File ("foo.txt")) {while (scanner.hasNext ()) {System.out.println (scanner.nextLine ());}} catch (FileNotFoundException e) {e.printStackTrace ();}

This will greatly reduce the number of lines of code that close the stream or database connection and reduce the number of errors caused by forgetting to close the stream / connection.

2 switch expression

Developers often encounter situations where they need to return a value from a conditional block, but the old syntax is not easy to solve.

Old grammar

Private String getUserRole (User user) {String userRole = ""; switch (user.getRole ()) {case 0: userRole = "Customer"; break; case 1: userRole = "Editor"; break; case 2: userRole = "Admin"; break Default: throw new IllegalStateException ("Unexpected value:" + user.getRole ());} return userRole;}

Like modern languages such as Swift, Java 12 introduces switch expressions, which you can return values based on conditions.

New grammar

Private String getUserRoleV2 (User user) {return switch (user.getRole ()) {case 0-> "Customer"; case 1-> "Editor"; case 2: / / for multi line expression use 'yield' keyword user.setRights (AuthRights.absolute); yield "Admin"; default-> throw new IllegalStateException ("Unexpected value:" + user.getRole ());};}

This greatly reduces the LOC (lines of code) in the project and makes it relatively easy to modify.

3 initialize with var

Java is essentially a strictly typed language, and the use of strictly typed definitions is a matter of developer preference. But support for type inference reduces code complexity, and Java 10 adds support for type inference of local variables.

Private void init () {var str = "Java 10"; / / infers String var list = new ArrayList (); var stream = list.stream (); / / infers Stream}

However, Java is still a statically typed language, and types are inferred only when sufficient information is available for initialization. Therefore, it is legal to initialize with var if the variable meets the following conditions:

It can only be a local variable (class members or function parameters are not supported)

Should be defined immediately after the declaration (define)

4 record (record)

One of the most common complaints about using Java requires a lot of code to make classes available, such as a bunch of toString or equals definitions, so the code looks verbose. Java 14 provides Record syntax to make type declarations more concise, which is useful when we need to bind multiple values under a class name.

This is an example of an article on the Oracle website that shows the advantages of using records

Var order = new FXOrderClassic (1, CurrencyPair.GBPUSD, Side.Bid, 1.25, LocalDateTime.now (), 1000)

Calls to standard objects like this need to define the type FXOrderClassic.

Old grammar

Public final class FXOrderClassic {private final int units; private final CurrencyPair pair; private final Side side; private final double price; private final LocalDateTime sentAt; private final int ttl Public FXOrderClassic (int units, CurrencyPair pair, Side side, double price, LocalDateTime sentAt, int ttl) {this.units = units; this.pair = pair; / / CurrencyPair is a simple enum this.side = side / / Side is a simple enum this.price = price; this.sentAt = sentAt; this.ttl = ttl;} public int units () {return units;} public CurrencyPair pair () {return pair;} public Side side () {return side;} public double price () {return price } public LocalDateTime sentAt () {return sentAt;} public int ttl () {return ttl;} @ Override public boolean equals (Object o) {if (this = = o) return true; if (o = = null | | getClass ()! = o.getClass ()) return false; FXOrderClassic that = (FXOrderClassic) o If (units! = that.units) return false; if (Double.compare (that.price, price)! = 0) return false; if (ttl! = that.ttl) return false; if (pair! = that.pair) return false; if (side! = that.side) return false; return sentAt! = null? SentAt.equals (that.sentAt): that.sentAt = = null;} @ Override public int hashCode () {int result; long temp; result = units; result = 31 * result + (pair! = null? Pair.hashCode (): 0); result = 31 * result + (side! = null? Side.hashCode (): 0); temp = Double.doubleToLongBits (price); result = 31 * result + (int) (temp ^ (temp > > 32)); result = 31 * result + (sentAt! = null? SentAt.hashCode (): 0); result = 31 * result + ttl; return result @ Override public String toString () {return "FXOrderClassic {" + "units=" + units + ", pair=" + pair + ", side=" + side + ", price=" + price + ", sentAt=" + sentAt + ", ttl=" + ttl +'} " }}

New grammar

Public record FXOrder (int units, CurrencyPair pair, Side side, double price, LocalDateTime sentAt, int ttl) {}

5 enhanced instance of

Java 14 introduces instanceof pattern matching, which means that explicit type conversions are no longer required when using instanceof's instance type checking.

Old grammar

Private Entries getEntries (User user) {if (user instanceof Editor) {Editor editor = (Editor) user; / / use editor specific methods var entries = editor.getEntries (); return entries;} return null;}

New grammar

Private Entries getEntries (User user) {if (user instanceof Editor editor) {/ / use group specific methods var entries = editor.getEntries (); return entries;} return null;}

6 text block

Supporting text blocks is nothing new, but it is a long-awaited feature for engineers in Java. Java developers are always eager to print multiline string text in an easier way rather than using annoying concatenation. The new version of Java supports multiline string text.

Old grammar

String html = "" + "\ n\ t" + "+"\ n\ t\ t "+"\ "Hurray! Java 14 is here\ "+"\ n\ t "+" + "\ n" + "

Using three quotes, you can use this feature, which is very convenient when using structured strings, such as writing files with certain alignment and spacing or adding multiline html blocks

New grammar

String html = "Hurray! Java 14 is here "

7 meaningful NPE (null pointer) messages

Null pointer exceptions (NPE) have always been a nightmare for Java developers and the most common problem encountered by developers.

However, NPE messages often do not provide enough information about the problem.

Var task = new Task (); final boolean isDataConsumed = task.getData (). GetBucket (). IsConsumed

In a code snippet, there may be multiple points of failure, such as

GetData () returns a null value

GetBucket () returns a null value

However, the following NPE error does not provide sufficient details about the issue.

To solve this problem, Oracle adds JEP 358 to provide useful NullPointExceptions

NullPointerException improves the availability of error messages generated by JVM by describing exactly which variable.

You can use this feature by adding the following flag to the Java command

-XX:+ShowCodeDetailsInExceptionMessages

Using this flag, JVM will provide more meaningful information to track the exact point of failure

Thank you for reading, the above is the content of "how to use the new Java features". After the study of this article, I believe you have a deeper understanding of how to use the new Java features, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report