JavaRush /Java Blog /Random EN /Java 13: New Features

Java 13: New Features

Published in the Random EN group
We have already gotten used to the fact that a new JDK release appears every six months. So far, this approach has justified itself, and the worries of some developers that they will not keep up with the updates have been in vain: there are few six-month changes and they are not as global as before. Well, novice programmers may not notice the innovation at all. Java 13: new features - 1However, it is better for future software developers to keep abreast of innovations. In this article, we will traditionally describe accepted extension proposals (JEPs). Java 13 includes only five JEPs and 76 new core library elements (of which almost half are simple additions to the java.io package).

JEP 355 : Text Blocks(Preview)

Let's start by changing the syntax of the language. The most significant of them are text blocks. They allow you to avoid escaping characters and know how to format strings. You may remember that JDK 12 did not include the expected Raw String Literals (JEP 326) feature for working with string literals. In Java 13, it was replaced by JEP 355 with its text blocks. You probably remember that in Java, a string is wrapped in double quotes. This is good, but the problem is that a line cannot occupy more than one line of the source file (to avoid confusion with a Java line, here we will call a file line a “line”). Well, let's go around and use, for example, the symbol \nif a break is required, or concatenation of multiline expressions. It doesn't turn out very nicely! Text literals with embedded HTML, XML, SQL, or JSON fragments are especially cumbersome. All this escaping, concatenation, and manual editing makes the code inconvenient to write and difficult to read. Text blocks try to solve this problem. They start uh... with triple double quotes and end with them (I know, it doesn't sound very good). Everything between the quotes is interpreted as part of the line, including newlines. Text blocks can be used exactly the same as standard text literals, and Java will compile the code the same way. Opening quotes must be followed by a line delimiter; text blocks cannot be used in one line, so the code
String smallBlock = """Only one line""";
will lead to the following errors:
TextBlock.java:3: error: illegal text block open delimiter sequence, missing line terminator
   String smallBlock = """Text Block""";
                          ^
TextBlock.java:3: error: illegal text block open delimiter sequence, missing line terminator
   String smallBlock = """Text Block""";
                                   	^
A simple HTML fragment can now be written like this:
String htmlBlock = """
               	<html>
                 	<body>
                   	<p>CodeGym Web page</p>
                 	</body>
               	<html>
         	     """;
Let's mention a few subtleties that are better to be aware of when using text blocks. The placement of the closing quotes turns out to be important: it determines how the occasional white space is handled. In the example above, the closing quotes are aligned with the indentation of the HTML text. In this case, the compiler will remove the indentation spaces, and as a result we will get a line like this:
<html>
  <body>
    <p>My web page</p>
  </body>
</html>
Note:such a line will contain a newline at the end of the line. If it is not needed, closing quotes “”” can be placed directly after the </html> tag. If we move the closing quotes closer to the left margin, this will change the amount of indentation removed. If we moved them two spaces to the left, we would add two spaces for indentation to each line line. Moving to the left edge will cause all padding to be preserved. Moving the quotes further to the right will have no effect and will not add any more indentation. Text blocks were included in JDK 13 as a preview feature. This means that they are not yet included in the corresponding Java language specification. That is, it is not clear whether this feature will become a permanent part of the language or whether it is just a guest here. Currently, developers can test the feature and give their opinion on it. The fate of text blocks will depend on it: the feature can be improved, and if you don’t like it, then it can be removed altogether. If you want to try out text blocks in practice, remember that preview features must be explicitly included in order to compile and run. Compilation:

javac --enable-preview --release 13 TextBlock.java
To run the application, you need to enable preview features:

java --enable-preview TextBlock
The class Stringhas three new methods that complement this language change:
  • formatted(): Format a string using the string itself as the format string. Equivalent to a challengeformat(this, args)
  • stripIndent(): Removes random spaces from a string. This is useful if you are reading multiline strings and want to apply the same whitespace exclusion as you would with an explicit declaration.
  • translateEscapes(): Returns a string with escape sequences (such as \ r), translated to the appropriate Unicode value.
It's interesting that these methods just appeared, but are already marked as deprecated ... this state of affairs suggests that they may be removed in a future version of the JDK. It seems a bit eccentric to add a new method and immediately abandon it. However, please note that these methods are associated with a preview feature that can be changed or removed. Perhaps introducing an annotation @PreviewFeaturewould help with such situations, but it is not included in the JDK yet (although with a high degree of probability it will appear in JDK 14).

JEP 354 : Switch Expression (Preview)

Java 12 introduced a proposal for a new form of writing expressions with a switch statement - JEP 325 . It turned out to be the very first preview feature and its fate proves that submitting proposals to users is a great idea. Prior to JDK 12, switchit could only be used as a statement that performs an action but does not return a result. But in Java 12 it allowed it to be used switchas an expression that returns a result that can be assigned to a variable. There were other changes to the syntax of case statements within switch. Let's look at an example from JEP to understand how this works.
int numberOfLetters;
switch(dayOfWeek) {
  case MONDAY:
  case FRIDAY:
  case SUNDAY:
    numberOfLetter = 6;
    break;
  case TUESDAY
    numberOfLetter = 7;
    break;
  case THURSDAY
  case SATURDAY
    numberOfLetter = 8;
    break;
  case WEDNESDAY
    numberOfLetter = 9;
    break;
  default:
   throw new IllegalStateException("Huh?: " + day);
}
In this example, we use value dayOfWeekto assign the value to numberOfLetters. Due to the peculiarities of the operator's work switch, this code is not the most beautiful and it is easy to make mistakes. First, if we forget to apply a statement breakto each group of case labels, we will default to the next group of case labels. This can lead to errors that are difficult to find. Second, we must define each group of case labels. If we forget, then, of course, we will get a compiler error, however, this option is not ideal. Our code is also quite verbose because each value dayOfWeekmust have its own case label. Using the new syntax, we get much cleaner and less error-prone code:
int numberOfLetters = switch (dayOfWeek) {
   case MONDAY, FRIDAY, SUNDAY -> 6;
   case TUESDAY -> 7;
   case THURSDAY, SATURDAY -> 8;
   case WEDNESDAY -> 9;
   default -> throw new IllegalStateException("Huh?: " + day);
};
Now we only need to make the assignment once (from the expression's return switchvalue) and can use a comma-separated list for the case labels. And since we don't use the operator break, we eliminate the problems associated with it. The expression syntax switchallows us to use older style syntax, so in JDK 12 we can write it like this:
int numberOfLetters = switch (dayOfWeek) {
  case MONDAY:
  case FRIDAY:
  case SUNDAY:
   break 6;
  case TUESDAY
   break 7;
  case THURSDAY
  case SATURDAY
   break 8;
  case WEDNESDAY
   break 9;
  default:
   throw new IllegalStateException("Huh?: " + day);
};
According to the Java community, using overloading breakto specify a return value can be confusing. The Java language also allows you to use break( and continue) with a label like the unconditional jump operator goto. JEP 354 changed this usage break, so in Java 13 our code changes slightly:
int numberOfLetters = switch (dayOfWeek) {
  case MONDAY:
  case FRIDAY:
  case SUNDAY:
   yield 6;
  case TUESDAY
   yield 7;
  case THURSDAY
  case SATURDAY
   yield 8;
  case WEDNESDAY
   yield 9;
  default:
   throw new IllegalStateException("Huh?: " + day);
};
The next three JEPs are associated with the Java Virtual Machine.

JEP 350 Dynamic CDS Archive

This extension allows you to dynamically archive classes at the end of a Java application's execution. CDS or Class Data Sharing allows you to pack all classes launched at startup into a special archive class data sharing, using the list of these same classes by default. This leads to a significant acceleration in launching applications and saving RAM. Previously, using AppCDS was a multi-step process that involved creating a list of relevant classes and using that list to create an archive that would be used for subsequent runs. Now all that is required is one launch of the application with the -XX: flag ArchiveClassesAtExitindicating the location where the archive will be written. With this approach, classes are automatically packaged into an archive after the application is stopped normally.

JEP 351 ZGC : Uncommit unused memory

A year ago, JDK 11 introduced ZGC, an experimental, scalable, low-latency garbage collector. At first, ZGC behaved rather strangely: it did not allow memory to be returned to the operating system, even if it was no longer needed. For some environments, such as containers, where resources are used by multiple services at the same time, this may limit the scalability and efficiency of the system. The ZGC heap consists of so-called ZPages. When ZPages are cleared during the garbage collection cycle, they are returned to the ZPageCache. The ZPages in this cache are ordered by how recently they were used. In Java 13, ZGC will return pages that have been identified as not being used for a long time to the operating system. This way they can be reused for other processes.

JEP 353 Reimplement the legacy Socket API

Both API implementations java.net.Socketare java.net.ServerSocketstill JDK 1.0. In this, and all subsequent JDKs, the implementation of these APIs uses several techniques (such as using the thread stack as an I/O buffer) that make them inflexible and difficult to maintain. To solve this problem, a new implementation was provided in JDK 13 NioSocketImpl. It no longer requires native code, making it easier to port to different platforms. This class also uses the existing buffer cache mechanism (avoiding the use of the thread stack for this purpose) and locking java.util.concurrentrather than synchronized methods. This will simplify integration with fibers from Project Loom .

New APIs

We mentioned earlier that Java 13 includes 76 new APIs in the base class libraries. They cover the following areas:
  • Unicode support updates.
  • Three new methods Stringto support text blocks (see JEP 255 description above).
  • Classes java.nionow have absolute (as opposed to relative) getand set methods. They, like the base abstract class Buffer, include a method slice()for retrieving part of the buffer.
  • force()The class method MappedByteBufferforces a buffer section to be written to its backing storage.
  • nio.FileSystemadds three new overloaded forms newFileSystem()for accessing the contents of a file as a file system.
  • A new interesting method has javax.annotation.processing.ProcessingEnvironmentappeared. isPreviewEnabled(). It will tell you whether preview features are enabled. This is interesting because the annotation mentioned above @PreviewFeaturewill not be available until JDK 14 is released.
  • DocumentBuilderFactoryand SAXParserFactoryget javax.xml.parsersthree new methods for creating namespace-aware instances.
The material is based on an article by Simon Ritter and official documentation .
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION