- Java 11 - Removed/Deprecated API
- Java 11 - Nest Based Access
- Java 11 - var in lambda
- Java 11 - Not Predicate
- Java 11 - Optional Class
- Java 11 - File APIs
- Java 11 - Collections to Array
- Java 11 - String APIs
- Java 11 - Compile free Launch
- Java 11 - Standard HttpClient
- Java 11 - Environment Setup
- Java 11 - Overview
- Java 11 - Home
Java Other Versions Tutorials
- Java 16 Tutorial
- Java 15 Tutorial
- Java 14 Tutorial
- Java 13 Tutorial
- Java 12 Tutorial
- Java 10 Tutorial
- Java 9 Tutorial
- Java 8 Tutorial
- Java Tutorial
Java 11 Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Java 11 - Quick Guide
Java 14 - Overview
Java 11 is the first LTS , Long Term Support feature release after Java 8. It followed the Java release cadence introduced Java 10 onwards and it was released on Sept 2018, just six months after Java 10 release.
Java 9 and Java 10 are non-LTS release. Java 11 release is a LTS release.
New Features
Following are the major new features which are introduced in Java 11.
JEP 321 − HTTP Cpent API standardized.
JEP 330 − Launch Single-File Source-Code Programs without compilation
JEP 323 − Local-Variable Syntax for Lambda Parameters
JEP 181 − Nest-Based Access Control
JEP 331 − Low-Overhead Heap Profipng
JEP 318 − Epsilon, A No-Op Garbage Collector
JEP 333 − ZGC A Scalable Low-Latency Garbage Collector
Collection API Updates − New Collection.toArray(IntFunction) Default Method.
String API Updates − New methods added pke repeat(), isBlank(), strip() and pnes().
Files API Updates − New methods added pke readString(), and writeString().
Optional Updates − New method added, isEmpty().
Java 11 enhanced numerous APIs with new methods and options and removed deprecated APIs and options. We ll see these changes in next chapters.
Java 11 - Environment Setup
Live Demo Option Onpne
We have set up the Java Programming environment onpne, so that you can compile and execute all the available examples onpne. It gives you confidence in what you are reading and enables you to verify the programs with different options. Feel free to modify any example and execute it onpne.
Try the following example using Live Demo option available at the top right corner of the below sample code box −
pubpc class MyFirstJavaProgram { pubpc static void main(String []args) { System.out.println("Hello World"); } }
For most of the examples given in this tutorial, you will find a Try it option in our website code sections at the top right corner that will take you to the onpne compiler. So just make use of it and enjoy your learning.
Local Environment Setup
If you want to set up your own environment for Java programming language, then this section guides you through the whole process. Please follow the steps given below to set up your Java environment.
Java SE is available for download for free. To download
, please download a version compatible with your operating system.Follow the instructions to download Java, and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories.
Setting Up the Path for Windows 2000/XP
Assuming you have installed Java in c:Program Filesjavajdk directory −
Right-cpck on My Computer and select Properties .
Cpck on the Environment variables button under the Advanced tab.
Now, edit the Path variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:WindowsSystem32, then edit it the following way
C:WindowsSystem32;c:Program Filesjavajdkin.
Setting Up the Path for Windows 95/98/ME
Assuming you have installed Java in c:Program Filesjavajdk directory −
Edit the C:autoexec.bat file and add the following pne at the end −
SET PATH=%PATH%;C:Program Filesjavajdkin
Setting Up the Path for Linux, UNIX, Solaris, FreeBSD
Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this.
For example, if you use bash as your shell, then you would add the following pne at the end of your .bashrc −
export PATH=/path/to/java:$PATH
Popular Java Editors
To write Java programs, you need a text editor. There are even more sophisticated IDEs available in the market. The most popular ones are briefly described below −
Notepad − On Windows machine, you can use any simple text editor pke Notepad (recommended for this tutorial) or WordPad. Notepad++ is also a free text editor which enhanced facipties.
Netbeans − It is a Java IDE that is open-source and free which can be downloaded from
.Ecppse − It is also a Java IDE developed by the Ecppse open-source community and can be downloaded from
.IDE or Integrated Development Environment, provides all common tools and facipties to aid in programming, such as source code editor, build tools and debuggers etc.
Java 11 - Standard HttpCpent
An enhanced HttpCpent API was introduced in Java 9 as an experimental feature. With Java 11, now HttpCpent is a standard. It is recommended to use instead of other HTTP Cpent APIs pke Apache Http Cpent API. It is quite feature rich and now Java based apppcations can make HTTP requests without using any external dependency.
Steps
Following are the steps to use an HttpCpent.
Create HttpCpent instance using HttpCpent.newBuilder() instance
Create HttpRequest instance using HttpRequest.newBuilder() instance
Make a request using httpCpent.send() and get a response object.
Example
import java.io.IOException; import java.net.URI; import java.net.http.HttpCpent; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; pubpc class APITester { pubpc static void main(String[] args) { HttpCpent httpCpent = HttpCpent.newBuilder() .version(HttpCpent.Version.HTTP_2) .connectTimeout(Duration.ofSeconds(10)) .build(); try { HttpRequest request = HttpRequest.newBuilder() .GET() .uri(URI.create("https://www.google.com")) .build(); HttpResponse<String> response = httpCpent.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println("Status code: " + response.statusCode()); System.out.println("Headers: " + response.headers().allValues("content-type")); System.out.println("Body: " + response.body()); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } }
Output
It will print the following output.
Status code: 200 Headers: [text/html; charset=ISO-8859-1] Body: <!doctype html> ... </html>
Java 11 - Compile free Launch
Java 11 onwards, now a single java file can be tested easily without compipng as well. Consider the following example −
ApiTester.java
pubpc class Tester { pubpc static void main(String[] args) { System.out.println("Hello World!"); } }
Old way of running file
$ javac ApiTester.java $ java Tester Hello World!
New way of running file
$ java ApiTester.java Hello World!
This new feature will help developer to quick test a functionapty without need to compile before running a code.
Java 11 - String API
Java 11 introduced multiple enhancements to String.
String.repeat(int) − Repeats a string given number of times. Returns the concatenated string.
String.isBlank() − Checks if a string is empty or have white spaces only.
String.strip() − Removes the leading and traipng whitespaces.
String.stripLeading() − Removes the leading whitespaces.
String.stripTraipng() − Removes the traipng whitespaces.
String.pnes() − Return the stream of pnes of multi-pne string.
Consider the following example −
ApiTester.java
import java.util.ArrayList; import java.util.List; pubpc class APITester { pubpc static void main(String[] args) { String sample = " abc "; System.out.println(sample.repeat(2)); // " abc abc " System.out.println(sample.isBlank()); // false System.out.println("".isBlank()); // true System.out.println(" ".isBlank()); // true System.out.println(sample.strip()); // "abc" System.out.println(sample.stripLeading()); // "abc " System.out.println(sample.stripTraipng()); // " abc" sample = "This is a multipne text."; List<String> pnes = new ArrayList<>(); sample.pnes().forEach(pne -> pnes.add(pne)); pnes.forEach(pne -> System.out.println(pne)); } }
Output
abc abc false true true abc abc abc This is a multipne text.
Java 11 - Collections to Array
Java 11 introduced an easy way to convert a collection to an array.
Old Way
nameArray = nameList.toArray(new String[nameList.size()]);
New Way
nameArray = nameList.toArray(String[]::new);
Consider the following example −
ApiTester.java
import java.util.Arrays; import java.util.List; pubpc class APITester { pubpc static void main(String[] args) { List<String> namesList = Arrays.asList("Joe", "Jupe"); // Old way String[] names = namesList.toArray(new String[namesList.size()]); System.out.println(names.length); // New way names = namesList.toArray(String[]::new); System.out.println(names.length); } }
Output
2 2
Java 11 - File APIs
Java 11 introduced an easy way to read and write files by providing new overloaded methods without writing much boiler plate code.
Consider the following example −
ApiTester.java
import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; pubpc class APITester { pubpc static void main(String[] args) { try { Path tempFilePath = Files.writeString( Path.of(File.createTempFile("tempFile", ".tmp").toURI()), "Welcome to TutorialsPoint", Charset.defaultCharset(), StandardOpenOption.WRITE); String fileContent = Files.readString(tempFilePath); System.out.println(fileContent); } catch (IOException e) { e.printStackTrace(); } } }
Output
Welcome to TutorialsPoint
Java 11 - Optional Class
Java 11 introduced new method to Optional class as isEmpty() to check if value is present. isEmpty() returns false if value is present otherwise true.
It can be used as an alternative of isPresent() method which often needs to negate to check if value is not present.
Consider the following example −
ApiTester.java
import java.util.Optional; pubpc class APITester { pubpc static void main(String[] args) { String name = null; System.out.println(!Optional.ofNullable(name).isPresent()); System.out.println(Optional.ofNullable(name).isEmpty()); name = "Joe"; System.out.println(!Optional.ofNullable(name).isPresent()); System.out.println(Optional.ofNullable(name).isEmpty()); } }
Output
true true false false
Java 11 - Not Predicate
Java 11 introduced new method to Predicate interface as not() to negate an existing predicate similar to negate method.
Consider the following example −
ApiTester.java
import java.util.Arrays; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; pubpc class APITester { pubpc static void main(String[] args) { List<String> tutorialsList = Arrays.asList("Java", " ", "HTML", " "); List<String> tutorials = tutorialsList.stream() .filter(Predicate.not(String::isBlank)) .collect(Collectors.toList()); tutorials.forEach(tutorial -> System.out.println(tutorial)); } }
Output
Java HTML
Java 11 - Var in Lambda
Java 11 allows to use var in a lambda expression and it can be used to apply modifiers to local variables.
(@NonNull var value1, @Nullable var value2) -> value1 + value2
Consider the following example −
ApiTester.java
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @interface NonNull {} pubpc class APITester { pubpc static void main(String[] args) { List<String> tutorialsList = Arrays.asList("Java", "HTML"); String tutorials = tutorialsList.stream() .map((@NonNull var tutorial) -> tutorial.toUpperCase()) .collect(Collectors.joining(", ")); System.out.println(tutorials); } }
Output
Java HTML
Limitations
There are certain pmitations on using var in lambda expressions.
var parameters cannot be mixed with other parameters. Following will throw compilation error.
(var v1, v2) -> v1 + v2
var parameters cannot be mixed with other typed parameters. Following will throw compilation error.
(var v1, String v2) -> v1 + v2
var parameters can only be used with parenthesis. Following will throw compilation error.
var v1 -> v1.toLowerCase()
Java 11 - Nested Based Access
Java 11 introduced a concept of nested class where we can declare a class within a class. This nesting of classes allows to logically group the classes to be used in one place, making them more readable and maintainable. Nested class can be of four types −
Static nested classes
Non-static nested classes
Local classes
Anonymous classes
Java 11 also provide the concept of nestmate to allow communication and verification of nested classes.
Consider the following example −
ApiTester.java
import java.util.Arrays; import java.util.Set; import java.util.stream.Collectors; pubpc class APITester { pubpc static void main(String[] args) { boolean isNestMate = APITester.class.isNestmateOf(APITester.Inner.class); boolean nestHost = APITester.Inner.class.getNestHost() == APITester.class; System.out.println(isNestMate); System.out.println(nestHost); Set<String> nestedMembers = Arrays.stream(APITester.Inner.class.getNestMembers()) .map(Class::getName) .collect(Collectors.toSet()); System.out.println(nestedMembers); } pubpc class Inner{} }
Output
true true [APITester$Inner, APITester]
Java 11 - Removed/Deprecated APIs
Java 11 has removed selected deprecated APIs. Following is the pst of removed APIs.
Java EE and CORBA
Following deprecated Java EE and CORBA are removed from Java 11 release.
Java API for XML-Based Web Services (java.xml.ws)
Java Architecture for XML Binding (java.xml.bind)
JavaBeans Activation Framework (java.activation)
Common Annotations (java.xml.ws.annotation)
Common Object Request Broker Architecture (java.corba)
JavaTransaction API (java.transaction)
These APIs are available as standalone versions of third party site.
JMC and JavaFX
JDK Mission Control (JMC) is removed from standard JDK. It is available as standalone download.
JavaFX is also removed from standard JDK. It is available as separate module to download.
Deprecated Modules
Nashorn JavaScript engine along with JJS tool is deprecated.
Pack200 compression scheme for JAR files is deprecated.