Key Points
jdk
environment - Path, JAVA_HOME, classpath
javac .\test\TestRegex.java
java test.TestRegex
Class.forName to load from imports list
- SDK use java <version>
- sdk list java | grep "installed"
References
Reference_description_with_linked_URLs_________________________ | Notes__________________________________________________________ |
---|
m.java |
|
m Spring |
|
m Groovy |
|
m Tomcat - Smart Service Model |
|
m REST API design and tools |
|
|
|
|
|
Java Install | Oracle provides restricted JDKs, OpenJDK project and platform vendors provide open JDK versions without license fees |
https://jdk.java.net/java-se-ri/8 | Links to Oracle restricted JDKs |
https://openjdk.java.net/install/ | OpenJDK binaries for Linux |
https://stackoverflow.com/questions/52975956/where-do-i-find-the-latest-openjdk-8 -ga-build-windows-10 _java_jdk_sources_stackoverflow.com-Where do I find the latest OpenJDK 8 GA build windows 10.pdf | Explain difference between Oracle JDK and Open JDK versions and sources |
https://adoptopenjdk.net/upstream.html | Open JDK Windows binaries from RedHat – good deal |
https://access.redhat.com/documentation/en-us/openjdk/8/html/openjdk_8_for_windows_getting_started_guide/getting_started_ with_openjdk_for_windows | RedHat getting started with OpenJDK |
https://installvirtual.com/install-openjdk-12-on-mac-os-using-brew/ | OpenJDK 12 install on MACOS |
https://www.zdnet.com/article/oracles-java-15-new-features-aim- to-keep-millions-away-from-languages-like-rust-kotlin/ jdk-15-zdnet.com-Oracles Java 15 New features aim to keep millions away from languages like Rust Kotlin.pdf | Oracle JDK 15 announced |
|
|
|
|
https://www.ibm.com/support/pages/how-determine-what-java-development-kits-jdks-are- installed-and-use-them-your-environment | IBM i Java versions - 2018 |
https://www.ibm.com/support/pages/supported-ibm-java-development-kit-jdk-versions- ibm-i-operating-system-version-and-release | IBM i Java version support by OS level Java on IBM i is WAY behind every other platform |
https://www.ibm.com/support/knowledgecenter/ssw_ibm_i_74/rzaha/rzahainstalljdk.htm | Install Java JDK 8 on IBM i v7.4 |
https://docs.oracle.com/javase/7/docs/technotes/tools/index.html | JDK tools and utilities |
|
|
|
|
Java Basics |
|
Why Java? 2022 view why-java-2022-Dont call it a comeback_ Why Java is still champ · GitHub.pdf file | Why Java? 2022 view |
https://www.jpassion.com/ | Jpassion annual subscription covers MANY courses beyond Java *** |
https://www.infoq.com/news/2023/03/java-20-so-far/ java-20-JDK 20 and JDK 21_ What We Know So Far.pdf FILE | Some JDK 20 Features **
|
JLS - Java Language Specification – JDK 17 url JLS - Java Language Specification – JDK 17 link | JDK 17 JLS - Java Language Spec ** |
https://devdocs.io/openjdk~17/ | OpenJDK 17 classes |
https://beginnersbook.com/java-tutorial-for-beginners-with-examples/ | Java Basics with great examples updated for Java 9 *** |
https://docs.oracle.com/javase/tutorial/index.html | Oracle Java Tutorials ** |
https://jenkov.com/tutorials/java/index.html https://jenkov.com/tutorials/java/modules.html | jenkov - simple Java Tutorials - current *** |
https://docs.oracle.com/javase/tutorial/java/index.html | Oracle JDK Java language basic Tutorials at JDK 8 |
https://docs.oracle.com/javase/tutorial/ | Java tutorials |
file:///C:/Users/Jim%20Mason/Google%20Drive/_docs/howto/jee/java-design-patterns -w_java59.pdf | Java Design Patterns - Gang of 4 |
https://www.guru99.com/java-tutorial.html | Very good on Java basics, algorithms |
https://howtodoinjava.com/java-version-wise-features-history/ | Java version history with features |
https://codete.com/blog/java-8-java-11-quick-guide/ | From Java 8 to Java 11 Guide - basics |
https://beginnersbook.com/java-tutorial-for-beginners-with-examples/ | Many free books including Java basics, streams, modules, lambda, |
https://docs.oracle.com/javase/tutorial/ | Old Oracle JSE 8 tutorials |
https://www.tutorialspoint.com/java/ | ok free site on Java |
https://www.learnjavaonline.org/ | very limited free Java basics |
https://javarevisited.blogspot.com/2011/01/how-classpath-work-in-java.html | free site with lots of interview questions |
https://snyk.io/blog/local-type-inference-java-cheat-sheet/ | Java syntax and coding tips |
https://en.wikipedia.org/wiki/Method_cascading | Java method chaining fine, cascading is a challenge |
file:///C:/Users/Jim%20Mason/Google%20Drive/_groups/nemug/Web%20Services%2 0on%20the%20IBM%20i%202%20per.pdf | Java Web Services intro session - Jim Mason |
https://developer.okta.com/blog/2020/04/08/kafka-streams | Tutorial - Java Streams with Kafka |
https://www.linkedin.com/posts/mraible_secure-kafka-streams-with-quarkus-and-java-activity-6653705632291573760-Ir2R | Tutorial - Quarkus and Java with Kafka Streams |
https://www.linkedin.com/posts/mraible_java-rest-api-showdown-which-is-the-best-activity-6621083078511087616-T_3j | Compare Micronaut, Quarkus, Spring frameworks |
Java checked and unchecked exceptions and throws vs handle | Handling Java errors and exceptions * |
https://www.geeksforgeeks.org/checked-vs-unchecked-exceptions-in-java/?ref=leftbar-rightbar | Java checked and unchecked exceptions |
|
|
More Java Basics |
|
javadocs JDK 11 | javadocs JDK 11 *** |
https://howtodoinjava.com/ | Java Tutorials |
https://beginnersbook.com/java-tutorial-for-beginners-with-examples/ | Java Beginner's Book - 2013 |
https://beginnersbook.com/2013/12/java-constructor-chaining-with-example/ | Chaining Java constructors |
https://beginnersbook.com/2013/05/aggregation/ | Reusable Nested Classes - Student.Address College.Address etc |
https://howtodoinjava.com/java-8-tutorial/ | Java 8 Features details |
https://docs.oracle.com/javase/tutorial/tutorialLearningPaths.html | Java SE Learning Path Tutorials |
https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html | Java Anonymous classes doc |
https://www.youtube.com/watch?v=8hA47LxykPo | New Java version features to JDK 15 * |
java-cloud-k8s-modernizing-enterprise-java-ebook-f32152-202210-en.pdf link java-cloud-k8s-modernizing-enterprise-java-ebook-f32152-202210-en.pdf file | Modern Java in the cloud strategies ** |
|
|
Advanced Java Topics |
|
Matt Raible Java Presentation Decks - speakerdeck.com | Great Java decks with github source code *** |
https://docs.oracle.com/javase/8/docs/technotes/guides/jpda/jdwp-spec.html | JDWP wire debug protocol - for remote debug tools |
https://stackify.com/java-remote-debugging/ https://drive.google.com/open?id=151Cy3kf8n4yfpC8915SaHi_D68IAn0TM | JDWP - tutorial - excellent tutorial to debug simple Spring boot app |
https://www.journaldev.com/1352/what-is-jmx-mbean-jconsole-tutorial https://drive.google.com/open?id=1awKvP1Sn01JoN2bmynsqvF-xiRlzRHkQ | JMX - Java MBeans overview |
https://stackoverflow.com/questions/16501/what-is-a-lambda-function | Lambda expressions in multiple languages |
https://beginnersbook.com/2017/10/java-lambda-expressions-tutorial-with-examples/ https://drive.google.com/open?id=1vaN39C7k8VhM0qbUABivWXmTh1hizUrH | Java Lambda expressions x0 - good overview |
http://tutorials.jenkov.com/java/lambda-expressions.html https://drive.google.com/open?id=1nChmdcv9pwAy16FxRBadXfFIHeOj8eKD | Java Lambda expressions x1 |
https://www.infoq.com/articles/java-14-feature-spotlight/ java-14-records-infoq.com-Java 14 Feature Spotlight Records.pdf https://cr.openjdk.java.net/~briangoetz/amber/datum.html java-record-concepts-2020-cr.openjdk.java-Data Classes and Sealed Types for Java.pdf | JDK 14 records feature |
https://www.youtube.com/channel/UCxoUc7Rar2q90Gu0nT2ffuQ?sub_confirmation=1 | Java Tutorials JCG Youtube channel - good short videos |
|
|
|
|
Related Topics |
|
17 Java frameworks compared - 2022. url. link |
|
m Spring and JHipster | Spring frameworks |
https://www.owasp.org/index.php/Main_Page | OWASP security project |
https://www.udemy.com/course/eclipse-java-tutorial-for-beginners | Free Java Eclipse tutorial |
|
|
Other Java resources, Tutorials
|
|
https://www.youtube.com/watch?v=3vauM7axnRs | Java Project Tutorial - Make Login and Register Form Step by Step Using NetBeans And MySQL Database |
https://sites.google.com/site/prahladswiki/tutorials/libreoffice-base-connect-to-any-database | Prahlad's Knowledge Wiki - free resources |
https://maven.apache.org/users/index. | Maven Users Guide |
| Gradle home |
https://redmonk.com/sogrady/2021/08/05/language-rankings-6-21/ | Java still very popular in 2021 - consider the easy way with Groovy |
https://www.infoq.com/java/ | Java news from InfoQ *** |
Spring Boot 3 and Spring Framework 6 Use Java 17 and Jakarta EE 9, Support Native Java with GraalVM | embeds observability through Micrometer with tracing and metrics creating native executables through static (AOT) compilation with GraalVM Native Image. executables start faster, less memory, smaller container images - see six-piece article series simplifies HTTP requests with HTTP interfaces, like Spring JPA simplifies database queries virtual threads complementing reactive programming, not replacing it. module system alignment remains part of our long-term technology strategy ( not now ) |
Major Spring Releases, Resilience4j, Open Liberty, GlassFish, Kotlin 1.8-Beta | support for generating native images with GraalVM improved observability with Micrometer and Micrometer Tracing. Ahead-Of-Time (AOT) compiles Java into native code for subsequent executions Spring Authorization Server updates to current version of OAuth 2.1 Spring for GraphQL Spring for Kafka ( RabbitMQ ) for sending messages. Message-driven POJOs with @KafkaListener annotations and a "listener container" . |
Spring Modulith Structures Spring Boot 3 Applications with Modules and Events | Spring Modulith, to structure monolithic Spring Boot 3 applications through modules and events Its modules don't use Java Platform Module System (JPMS), but map to plain Java packages. Modules have an API, but Spring Modulith encourages using Spring application events These events can be automatically persisted to an event log. Spring Modulith also eases the testing of modules and events. |
|
|
Java Performance Tips |
|
Java JVM configuration tips to fit Hyperledger Fabric server use cases |
|
https://dzone.com/articles/playing-with-graal-vm for statically compiled Java |
|
Tuning Alpine JVM tutorials |
|
Key Concepts
Ubuntu - After JDK install, set JAVA_HOME default
Compare JDK versions on support
https://whichjdk.com/
whichjdk.com-Which Version of JDK Should I Use.pdf. link
JDK Version | Type | Release Date | Highlights | Recommendation |
---|
8 | LTS | 03/2014 | Lambdas | Last LTS version under previous release model. Free updates by Oracle ended, but still maintained by others. Upgrade to a 11 or 17 within the next months! |
9 | Feature | 09/2017 | Modules | New release model was introduced. EOL. Upgrade to 11 or 17 now! |
10 | Feature | 03/2018 | var | EOL. Upgrade to 11 or 17 now! |
11 | LTS | 09/2018 | New HTTP Client | Widely used LTS version. Plan upgrade to version 17 within the next months. |
12 | Feature | 03/2019 |
| EOL. Upgrade to 17 now! |
13 | Feature | 09/2019 |
| EOL. Upgrade to 17 now! |
14 | Feature | 03/2020 | Switch expressions | EOL. Upgrade to 17 now! |
15 | Feature | 09/2020 | Text blocks | EOL. Upgrade to 17 now! |
16 | Feature | 03/2021 | Records | EOL. Upgrade to 17 now! |
17 | LTS | 09/2021 | Sealed Classes | Current LTS version. Update to 17.0.3+ now! |
18 | Feature | 03/2022 | UTF-8 by Default | Stick to 17! It is a short term release without significant features. You might want to check if you run in any issues with “UTF-8 by Default” by setting -Dfile.encoding=UTF-8 in your current JDK. |
19 | Feature | 09/2022 | Preview and incubator features, only | Stick to 17! If you upgraded to 18 before, upgrade now to 20. |
20 | Feature | 03/2023 | Preview and incubator features, only | Stick to 17! If you upgraded to 19 before, upgrade now to 20.
|
JDK Distributions
https://stackoverflow.com/questions/53305934/differences-amazon-corretto-and-openjdk
To summarize, you have 3 options:
- Use OpenJDK for free, but upgrade every 6 months to get updates
- Use a paid JDK from Oracle or another vendor
- Use Corretto for free, and get free updates for several years
As you can see, Corretto is a great choice if you want to stay secure and up-to-date, don't want to pay money, and don't want to be constantly upgrading to a new version.
Here are the current end of life dates for Corretto:
- version 8 LTS June 2026
- version 11 LTS September 2027
- version 17 LTS October 2029
Non-LTS versions are available as well, but are supported for a shorter period of time.
MACOS - After JDK install, set JAVA_HOME default
set default jdk on macos
https://kodejava.org/how-do-i-set-the-default-java-jdk-version-on-mac-os-x/
1> list installed JDKs
ls -l /Library/Java/JavaVirtualMachines
drwxr-xr-x 3 root wheel 96 Sep 7 10:20 adoptopenjdk-11.jdk
drwxr-xr-x 3 root wheel 96 Jan 7 2015 jdk1.8.0_25.jdk
2> for a given JDK version, export JAVA_HOME execution JDK
export JAVA_HOME=`/usr/libexec/java_home -v 11`
3> check default JDK
java -version
openjdk version "11.0.8" 2020-07-14
OpenJDK Runtime Environment AdoptOpenJDK (build 11.0.8+10)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.8+10, mixed mode)
Install a Java JDK manually on macos
https://www.codejava.net/java-se/install-openjdk-18-on-macos
target JDKs in 2023, JDK 11, JDK 19 from java.
video on sdkman — https://www.youtube.com/watch?v=ZywEiw3EO8A
sdkman article - https://mydeveloperplanet.com/2022/04/05/how-to-manage-your-jdks-with-sdkman/
curl -s "https://get.sdkman.io" | bash
### Please open a new terminal, or run the following in the existing one:
source "/home/<your user>/.sdkman/bin/sdkman-init.sh"
### Then issue the following command:
sdk help
sdk list java
Install a Java JDK using brew - very limited options found
brew search --formulae java.
As you can see below, only java11
and java
are available.
If no formula exists for a brew Java install for the version you want, check the OpenJDK site for Java OpenJDK installs in a container
Windows - After JDK install, set JAVA_HOME default
set javapath=d:\dsfw\server\java\jdk1.8.0_212
set javabin=d:\dsfw\server\java\jdk1.8.0_212\bin
SET JAVA_HOME=%javapath%
SET CLASSPATH=.;%JAVA_HOME%\lib
set Path=.;%javabin%;%Path%
java -version
startup scripts
java8.bat.txt
set javapath=d:\dsfw\server\java\jdk1.8.0_212
set javabin=d:\dsfw\server\java\jdk1.8.0_212\bin
SET JAVA_HOME=%javapath%
SET CLASSPATH=.;%JAVA_HOME%\lib
set Path=.;%javabin%;%Path%
java -version
groovy_start2.bat.txt
set GROOVY_HOME=d:\dsfw\server\groovy
set Path=;%Path%;d:\dsfw\server\groovy\bin
groovy --version
groovy3_start.bat.txt
https://docs.oracle.com/javase/7/docs/technotes/tools/index.html
General
- General Information (file structure, classpath, how classes are found, changes)
- Enhancements
- (enhancements in JDK 7)
Standard JDK Tools and Utilities
- Basic Tools (appletviewer, apt, extcheck, jar, java, javac, javadoc, javah, javap, jdb)
- Security Tools (keytool, jarsigner, policytool, kinit, klist, ktab)
- Internationalization Tools (native2ascii)
- Remote Method Invocation (RMI) Tools (rmic, rmiregistry, rmid, serialver)
- Java IDL and RMI-IIOP Tools (tnameserv, idlj, orbd, servertool)
- Java Deployment Tools (javafxpackager, pack200, unpack200)
- Java Web Start Tools (javaws)
- Java Troubleshooting, Profiling, Monitoring and Management Tools (jcmd, jconsole, jmc, jvisualvm)
- Java Web Services Tools (schemagen, wsgen, wsimport, xjc)
Experimental JDK Tools and Utilities
NOTE - The tools described in this section are unsupported and experimental in nature and should be used with that in mind. They might not be available in future JDK versions.
- Monitoring Tools (jps, jstat, jstatd)
- Troubleshooting Tools (jinfo, jhat, jmap, jsadebugd, jstack)
- Scripting Tools (jrunscript)
Troubleshooting Documentation
- Java™ SE Troubleshooting web site (tools, options, and other items for use in analyzing problems)
Simple RDBs that work for Java client apps ( Derby, H2, Sqlite )
https://db-engines.com/en/system/Derby%3BH2%3BSQLite
db.apache.org/derby/manuals/index.html
www.h2database.com/html/main.html
www.sqlite.org/docs.html
Java Class Loading Concepts
https://docs.oracle.com/javase/8/docs/technotes/tools/windows/findingclasses.html
chapter covers the following topics:
The tools classes in the tools.jar
file are only used to run the javac
and javadoc
commands. The tools classes are not used to resolve source code references unless the tools.jar
file is in the user class path.
A programmer might want to resolve boot class or extension class references with an alternative Java platform implementation. Both the javac
and javadoc
commands support this with their -bootclasspath
and -extdirs
options. Use of these options does not modify the set of class files used to run the javac
or javadoc commands themselves
Optional Security Policy for a Class Loader will affect how classes are loaded
To be used, a class or interface must be loaded by a class loader. Use of a particular class loader determines a security policy associated with the class loader.
A program can load a class or interface by calling the loadClass
method of a class loader object. But usually a program loads a class or interface by referring to it. This invokes an internal class loader, which can apply a security policy to extension and user classes. If the security policy has not been enabled, all classes are trusted. Even if the security policy is enabled, it does not apply to bootstrap classes, which are always trusted.
When enabled, security policy is configured by system and user policy files. The Java platform SDK includes a system policy file that grants trusted status to extension classes and places basic restrictions on user classes.
Finding class jars
jim-macbook:~ jimmason$ find /Library/java -iregex '.*rt\.jar.*' 2>/dev/null -exec ls -l {} \;
-rw-rw-r--@ 1 root wheel 66103336 Sep 17 2014 /Library/java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/jre/lib/rt.jar
-rw-rw-r-- 1 root wheel 17362230 Sep 16 2014 /Library/java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/jre/lib/ext/jfxrt.jar
Creating a custom class loader for user classes
https://www.infoworld.com/article/2077260/learn-java-the-basics-of-java-class-loaders.html
List all classes in a specific Class loader
https://www.baeldung.com/java-list-classes-class-loader
class-loading-lister-baeldung-List All Classes Loaded in a Specific Class Loader.pdf
Find file system location for a Class
final File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
from a web app
final File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getURI().getPath());
Java Tutorials
https://howtodoinjava.com/
Core Java
- Core Java Tutorial
- Java 12 Tutorial
- Java 11 Tutorial
- Java 10 Tutorial
- Java 9 Tutorial
- Java 8 Tutorial
- Java 7 Tutorial
- Object Oriented Principles
- Java Concurrency Tutorial
- Java Collections Tutorial
- Java IO Tutorial
- Date Time Tutorial
- Enum Tutorial
- Java Exceptions
- Generics Tutorial
- Garbage Collection Tutorial
- Java Serialization Tutorial
- String Class Tutorial
- Java Regular Expression Tutorials
- NIO Tutorials
Key Java Version Summaries
https://www.aegissofttech.com/articles/java-8-9-10-11-new-key-features-and-enhancements.html
Java 8, 9, 10, 11 and beyond delivering new features to the JDK. JDK 8 had come up with so many new features like lambda expression, functional interface and so on. But post that Java 9 got released in 2017 with a very big change that is the introduction of modularity. Then after one year of Java 9, Java 10 got released in the year 2018 with some new features and some enhancements of local variable type and garbage collection. JDK 9 and JDK 10 are feature releases of Java. Feature release means we will get only two scheduled updates. Java 11 got released in 2018 where java has open-sourced some of its closed sourced parts of JDK through OpenJDK release. JDK 11 also has removed so many packages from it like Applets, JavaFX, Web start, etc.
Now Oracle has come up with a new release Model, that every 6 months there will be a release of a new major version of JDK. As the number of major releases of java will get increased, because of this Oracle, will not be providing long-term support for all the releases. Oracle has come up with a plan that only one Long term support release every three years.
Lambda expression definition
https://gist.github.com/ericelliott/414be9be82128443f6df
Anonymous function means "function without a name".
This is one of the relatively few cases where the Wikipedia definition of a word, while not entirely wrong, is misleading. Lambdas and anonymous functions are distinct ideas.
These ideas are commonly confused because in many programming languages (and lambda calculus) all lambdas are anonymous or vise verse.
In JavaScript, not all lambdas are anonymous, and not all anonymous functions are lambdas, so the distinction has some practical meaning.
In Groovy, we use closures as first class objects ( returned value or parameter passed to a function )
In computer science, the most important, defining characteristic of a lambda
expression is that it is used as data. That is, the function is passed as
an argument to another function, returned as a value from a function, or
assigned to variables or data structures.
This is basically the definition of a first class function. In JavaScript, you
can use any function as a lambda expression because functions are first class.
However, that does not mean that all JavaScript functions are therefore lambda
expressions. For instance, this expression defines a function which gets
immediately invoked and then dropped on the floor rather than passed,
exported, or assigned. In other words, the function is not used as data.
Instead, it's used for a side-effect (logging this text to the console).
Java Lambda Quick Start
https://www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda-QuickStart/index.html
https://dev.java/learn/lambda-expressions/
Lambda expressions were a powerful addition to the Java language starting in Java 8. This is a series of tutorials aimed at introducing the concept of lambdas while incrementally teaching how to use them in practice as you progress through each tutorial.
The tutorials in this series are listed below. We recommend starting with the first and working your way through, but you are free to start wherever you'd like!
- Writing Your First Lambda Expression
Writing your first lambda, finding the type of a lambda.
- Using Lambdas Expressions in Your Application
Discovering the most useful functional interfaces of the JDK.
- Writing Lambda Expressions as Method References
Understanding Method References.
- Combining Lambda Expressions
Using Default and Static Methods to Combine and Create Lambdas.
- Writing and Combining Comparators
Creating and Combining Comparators Using Lambda Expressions.
Lambda expression tutorial
https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
Lambda expressions let you express instances of single-method classes more compactly.
Lamba expression vs Java anonymous inner class to implement function interface
https://beginnersbook.com/2017/10/java-lambda-expressions-tutorial-with-examples/
To use lambda expression, you need to either create your own functional interface or use the pre defined functional interface provided by Java. An interface with only single abstract method is called functional interface(or Single Abstract method interface), for example: Runnable, callable, ActionListener etc.
Inner Class example
Prior to java 8 we used the anonymous inner classe to implement the only abstract method of functional interface.
import java.awt.*;
import java.awt.event.*;
public class ButtonListenerOldWay {
public static void main(String[] args) {
Frame frame=new Frame("ActionListener Before Java8");
Button b=new Button("Click Here");
b.setBounds(50,100,80,50);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("Hello World!");
}
});
frame.add(b);
frame.setSize(200,200);
frame.setLayout(null);
frame.setVisible(true);
}
}
Lambda expression example
Lambda expression only has a parm list and a body
return type is inferred at runtime
To use lambda expression, you need to either create your own functional interface or use the pre defined functional interface provided by Java. An interface with only single abstract method is called functional interface(or Single Abstract method interface), for example: Runnable, callable, ActionListener etc.
import java.awt.*;
public class ButtonListenerNewWay {
public static void main(String[] args) {
Frame frame=new Frame("ActionListener java8");
Button b=new Button("Click Here");
b.setBounds(50,100,80,50);
b.addActionListener(e -> System.out.println("Hello World!"));
frame.add(b);
frame.setSize(200,200);
frame.setLayout(null);
frame.setVisible(true);
}
}
Lambdas are backward compatible so you can use them in existing API when you migrate your project to java 8.
Lambda expression example 2 - implements a custom interface
Define a custom functional interface and implement with a Lambda expression
@FunctionalInterface
interface MyFunctionalInterface {
//A method with single parameter
public int incrementByFive(int a);
}
public class Example {
public static void main(String args[]) {
// lambda expression with single parameter num
MyFunctionalInterface f = (num) -> num+5;
System.out.println(f.incrementByFive(22));
}
}
Lambda Expression Examples in Different Languages
https://stackoverflow.com/questions/16501/what-is-a-lambda-function
ES6
const adder = x => y => x + y;
add5 = adder(5);
add5(1) == 6
R
adder <- function(x) {
function(y) x + y
}
add5 <- adder(5)
add5(1)
#> [1] 6
Java - method chaining vs method cascading
https://en.wikipedia.org/wiki/Method_cascading
Smalltalk
For example, the "add an object to a collection" method (Collection>>add: anObject
) returns the object that was added, not the collection. Thus to use this in a cascade in an assignment statement, the cascade must end with yourself
, otherwise the value will just be the last element added, not the collection itself:
all := OrderedCollection new
add: 5;
add: 7;
yourself.
Java Records simplify DTO use
https://www.javacodegeeks.com/2021/04/java-16-records-with-jpa-and-jooq.html
Thanks to Java 16 Records this is now much simpler:
1 2 | public record EmployeeDTO(String employeeName, String departmentName) {
}
|
This Record will contain the required constructor and also the methods to get the employeeName and the departmentName so it’s a perfect fit for JPAs constructor expression!
Java Threads
With shared objects across threads
The reason for data inconsistency is because updating any field value is not an atomic process, it requires three steps; first to read the current value, second to do the necessary operations to get the updated value and third to assign the updated value to the field reference. Let’s check this with a simple program where multiple threads are updating the shared data.
Thread Safety Methods
Thread safety in java is the process to make our program safe to use in multithreaded environment, there are different ways through which we can make our program thread safe.
- Synchronization is the easiest and most widely used tool for thread safety in java.
- Use of Atomic Wrapper classes from java.util.concurrent.atomic package. For example AtomicInteger
- Use of locks from java.util.concurrent.locks package.
- Using thread safe collection classes, check this post for usage of ConcurrentHashMap for thread safety.
- Using volatile keyword with variables to make every thread read the data from memory, not read from thread cache.
jOOQ SQL Projection
Beside JPA there is another great solution for accessing relational database systems: jOOQ
With jOOQ we can write type-safe SQL in Java. And very often we also want DTOs as a result. Also here Java Records shine:
1 2 3 4 | List<EmployeeDTO> employees = dsl
.select(EMPLOYEE.NAME, DEPARTMENT.NAME)
.from(EMPLOYEE).join(DEPARTMENT).on(EMPLOYEE.DEPARTMENT_ID.eq(DEPARTMENT.ID))
.fetchInto(EmployeeDTO. class );
|
Java Version History - Features
https://howtodoinjava.com/java-version-wise-features-history/
Java 18 Features
Java 18 GA was released on 22 March 2022. It has nine new features, including a simple web server and another preview of pattern matching for switch
.
The below listed 14 JEPs are part of Java 18.
- JEP-400: UTF-8 by Default
- JEP-408: Simple Web Server
- JEP-413: Code Snippets in Java API Documentation
- JEP-416: Reimplement Core Reflection with Method Handles
- JEP-417: Vector API (Third Incubator)
- JEP-418: Internet-Address Resolution SPI
- JEP-419: Foreign Function & Memory API (Second Incubator)
- JEP-420: Pattern Matching for switch (Second Preview)
- JEP-421: Deprecate Finalization for Removal
Java 17 Features
Java 17 was released on September 14, 2021. Java 17 is an LTS (Long Term Support) release, like Java 11 and Java 8. Spring 6 and Spring boot 3 will have first-class support for Java 17. So it is a good idea to plan for upgrading to Java 17.
The below listed 14 JEPs are part of Java 17.
- (JEP-306) Restore Always-Strict Floating-Point Semantics
- (JEP-356) Enhanced Pseudo-Random Number Generators
- (JEP-382) New macOS Rendering Pipeline
- (JEP-391) macOS/AArch64 Port
- (JEP-398) Deprecate the Applet API for Removal
- (JEP-403) Strongly Encapsulate JDK Internals
- (JEP-406) Pattern Matching for switch (Preview)
- (JEP-407) Remove RMI Activation
- (JEP-409) Sealed Classes
- (JEP-410) Remove the Experimental AOT and JIT Compiler
- (JEP-411) Deprecate the Security Manager for Removal
- (JEP-412) Foreign Function & Memory API (Incubator)
- (JEP-414) Vector API (Second Incubator)
- (JEP-415) Context-Specific Deserialization Filters
Java 16 Features
Java 16 was released on 16 March 20121. It was largely a maintenance release, except it made the Java Records and Pattern matching the standard features of Java language.
Java 15 Features
Java 15 was released on 15th Sep’2020. It continues support for various preview features in previous JDK releases; and also introduced some new features.
Java 14 Features
Java 14 (released on March 17, 2020) is the latest version available for JDK. Let’s see the new features and improvements, it brings for developers and architects.
Java 13 Features
Java 13 (released on September 17, 2019) had fewer developer-specific features. Let’s see the new features and improvements, it brought for developers and architects.
- JEP 355 – Text Blocks (Preview)
- JEP 354 – Switch Expressions Enhancements (Preview)
- JEP 353 – Reimplement the Legacy Socket API
- JEP 350 – Dynamic CDS Archive
- JEP 351 – ZGC: Uncommit Unused Memory
- FileSystems.newFileSystem() Method
- DOM and SAX Factories with Namespace Support
Java 12 Features
Java 12 (released on March 19, 2019) is latest version available for JDK. Let’s see the new features and improvements, it brings for developers and architects.
- Collectors.teeing() in Stream API
- String API Changes
- Files.mismatch(Path, Path)
- Compact Number Formatting
- Support for Unicode 11
- Switch Expressions (Preview)
Java 11 Features
Java 11 (released on September 2018) includes many important and useful updates. Let’s see the new features and improvements, it brings for developers and architects.
- HTTP Client API
- Launch Single-File Programs Without Compilation
- String API Changes
- Collection.toArray(IntFunction)
- Files.readString() and Files.writeString()
- Optional.isEmpty()
Java 10 Features
After Java 9 release, Java 10 came very quickly. Unlike it’s previous release, Java 10 does not have that many exciting features, still it has few important updates which will change the way you code, and other future Java versions.
- JEP 286: Local Variable Type Inference
- JEP 322: Time-Based Release Versioning
- JEP 304: Garbage-Collector Interface
- JEP 307: Parallel Full GC for G1
- JEP 316: Heap Allocation on Alternative Memory Devices
- JEP 296: Consolidate the JDK Forest into a Single Repository
- JEP 310: Application Class-Data Sharing
- JEP 314: Additional Unicode Language-Tag Extensions
- JEP 319: Root Certificates
- JEP 317: Experimental Java-Based JIT Compiler
- JEP 312: Thread-Local Handshakes
- JEP 313: Remove the Native-Header Generation Tool
- New Added APIs and Options
- Removed APIs and Options
Java 9 Features
Java 9 was made available on September, 2017
. The biggest change is the modularization i.e. Java modules.
Some important features/changes in Java 9 are:
Please see the updated release info here.
Java 8 Features
Release Date : March 18, 2014
https://docs.oracle.com/javase/8/docs/
Code name culture is dropped. Included features were:
Java SE 7 Features
Release Date : July 28, 2011
This release was called “Dolphin”. Included features were:
Java SE 6 Features
Release Date : December 11, 2006
This release was called “Mustang”. Sun dropped the “.0” from the version number and version became Java SE 6. Included features were:
- Scripting Language Support
- Performance improvements
- JAX-WS
- JDBC 4.0
- Java Compiler API
- JAXB 2.0 and StAX parser
- Pluggable annotations
- New GC algorithms
J2SE 5.0 Features
Release Date : September 30, 2004
This release was called “Tiger”. Most of the features, which are asked in java interviews, were added in this release.
Version was also called 5.0 rather than 1.5. Included features are listed down below:
J2SE 1.4 Features
Release Date : February 6, 2002
This release was called “Merlin”. Included features were:
assert
keyword- Regular expressions
- Exception chaining
- Internet Protocol version 6 (IPv6) support
- New I/O; NIO
- Logging API
- Image I/O API
- Integrated XML parser and XSLT processor (JAXP)
- Integrated security and cryptography extensions (JCE, JSSE, JAAS)
- Java Web Start
- Preferences API (java.util.prefs)
J2SE 1.3 Features
Release Date : May 8, 2000
This release was called “Kestrel”. Included features were:
- HotSpot JVM
- Java Naming and Directory Interface (JNDI)
- Java Platform Debugger Architecture (JPDA)
- JavaSound
- Synthetic proxy classes
J2SE 1.2 Features
Release Date : December 8, 1998
This release was called “Playground”. This was a major release in terms of number of classes added (almost trippled the size). “J2SE” term was introduced to distinguish the code platform from J2EE and J2ME. Included features were:
strictfp
keyword- Swing graphical API
- Sun’s JVM was equipped with a JIT compiler for the first time
- Java plug-in
- Collections framework
JDK 1 Features
Release Date : January 23, 1996
This was the initial release and was originally called Oak. This had very unstable APIs and one java web browser named WebRunner.
The first stable version, JDK 1.0.2, was called Java 1.
On February 19, 1997, JDK 1.1 was released havind a list of big features such as:
- AWT event model
- Inner classes
- JavaBeans
- JDBC
- RMI
- Reflection which supported Introspection only, no modification at runtime was possible.
- JIT (Just In Time) compiler for Windows
One may say introspection is anything that allows code to test what something is ("What am I?"), whereas reflection is the ability to manipulate the program structure itself.
Java 8 to Java 11 Guide
https://codete.com/blog/java-8-java-11-quick-guide/
Java 8
https://howtodoinjava.com/java-8-tutorial/
see above m Java Basics#Lambdaexpressiondefinition
https://howtodoinjava.com/java8/lambda-expressions/
Ex - stream filter using collect and list
https://www.mkyong.com/java8/java-8-streams-filter-examples/
//NowJava8.java
package com.mkyong.java8;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class NowJava8 {
public static void main(String[] args) {
List<String> lines = Arrays.asList("spring", "node", "mkyong");
List<String> result = lines.stream() // convert list to stream
.filter(line -> !"mkyong".equals(line)) // we dont like mkyong
.collect(Collectors.toList()); // collect the output and convert streams to a List
result.forEach(System.out::println); //output : spring, node
}
}
Ex 2 - Stream filter, findAny, orElse example
https://www.mkyong.com/java8/java-8-streams-filter-examples/
For Person class
package com.mkyong.java8;
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
//gettersm setters, toString
}
Using old Java search methods
package com.mkyong.java8;
import java.util.Arrays;
import java.util.List;
public class BeforeJava8 {
public static void main(String[] args) {
List<Person> persons = Arrays.asList(
new Person("mkyong", 30),
new Person("jack", 20),
new Person("lawrence", 40)
);
Person result = getStudentByName(persons, "jack");
System.out.println(result);
}
private static Person getStudentByName(List<Person> persons, String name) {
Person result = null;
for (Person temp : persons) {
if (name.equals(temp.getName())) {
result = temp;
}
}
return result;
}
}
Using new Stream methods
package com.mkyong.java8;
import java.util.Arrays;
import java.util.List;
public class NowJava8 {
public static void main(String[] args) {
List<Person> persons = Arrays.asList(
new Person("mkyong", 30),
new Person("jack", 20),
new Person("lawrence", 40)
);
Person result1 = persons.stream() // Convert to steam
.filter(x -> "jack".equals(x.getName())) // we want "jack" only
.findAny() // If 'findAny' then return found
.orElse(null); // If not found, return null
System.out.println(result1);
Person result2 = persons.stream()
.filter(x -> "ahmook".equals(x.getName()))
.findAny()
.orElse(null);
System.out.println(result2);
}
}
Ex 3 - Stream filter and map example
package com.mkyong.java8;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class NowJava8 {
public static void main(String[] args) {
List<Person> persons = Arrays.asList(
new Person("mkyong", 30),
new Person("jack", 20),
new Person("lawrence", 40)
);
String name = persons.stream()
.filter(x -> "jack".equals(x.getName()))
.map(Person::getName) //convert stream to String
.findAny()
.orElse("");
System.out.println("name : " + name);
List<String> collect = persons.stream()
.map(Person::getName)
.collect(Collectors.toList());
collect.forEach(System.out::println);
}
}
Predicate
Optionals
see below m Java Basics#JavaOptionalsasreturnobjects
Nashorn – JavaScript runtime which allows developers to embed JavaScript code within applications
Annotation on Java Types
Unsigned Integer Arithmetic
Repeating annotations
New Date and Time API
Statically-linked JNI libraries
Launch JavaFX applications from jar files
Remove the permanent generation from GC
We are all familiar with Java 8 and its ingenious features, but over 4 years have passed from the day of Java 8 release and Java has made a few more big steps forward, with which not all of us had a chance to familiarize. And that’s definitely high time to make up for it, because during this time we already had Java 9 release, which had been quickly superseded by Java 10 and there is Java 11 release just around the corner, which is going to be an important release, because similarly to Java 8, it will be a long-term-support version.
New Java release cycle
Oracle has announced that after releasing Java 9, they are changing the release cycle scheme to a much faster one. Instead of releasing only major increments twice a decade, we’ll be getting Java updates twice a year and a LTS version every three years. That is a big shift and in our opinion a very good response to accusations that Java is not adapting to market needs fast enough.
That said, Java 9 was released in 2017 with immediate plan for being superseded by Java 10 in March 2018. Similarly Java 11 is planned to replace Java 10 in September 2018.
Java 9
Project Jigsaw
The flagship feature of Java 9 was Jigsaw project that introduced modularity to monolithic Java SE ecosystem. The primary goal of the Jigsaw project was to make the Java SE Platform and the JDK more easily scalable down to small computing devices.
Modularization of the JDK enables the source code to be completely restructured in order to make it easier to maintain. Module is a self-describing collection of code, data and resources. It consists of module-info.java file and one or more packages. Modules offer stronger encapsulation than jars.
Let’s say that we have two modules in our application:
Each module has a module-info.java file that describes module’s dependencies. Module com.codete.demo.service contains two packages: price and quantity. We want to expose only price package to third-party modules and keep quantity private. What we need to do is to define it in module-info.java file:
module com.codete.demo.services {
exports com.codete.demo.services.price;
}
Class PricePresenter is defined in com.codete.demo.front module and requires PriceService defined in com.codete.demo.service, so we need to reflect it in module-info.java:
module com.codete.demo.front {
requires com.codete.demo.services;
}
JShell
Java 9 finally provided a Read-Eval-Print Loop (REPL) tool. This is an interactive programming tool which is continually reading user input, evaluating it and printing the output value or a description of the state change the input caused.
Let’s declare a sample stream:
jshell>
Stream<String> names = Stream.of("John", "George", "Susan","Tom");
names ==> java.util.stream.ReferencePipeline$Head@6e1567f1
Then create method that will print it for us:
jshell>
public void printStringStream(Stream<String> input){
System.out.println(input.collect(Collectors.toList()));
}
| created method printStringStream(Stream<String>)
Now, invoke already declared method:
jshell>
printStringStream(names);
[John, George, Susan, Tom]
Jshell supports Tab completion to type commands faster. For example put “names.co” in your Jshell command prompt and then press Tab key:
jshell> names.co
You will see all possible methods, that you can invoke on above stream, that starts with “co”.
Except Java language expressions, Jshell provides it’s own commands:
jshell> /imports
Will return list of imports. Please notice, that Jshell by default returns couple of them:
| import java.io.*
| import java.math.*
| import java.net.*
| import java.nio.file.*
| import java.util.*
| import java.util.concurrent.*
| import java.util.function.*
| import java.util.prefs.*
| import java.util.regex.*
| import java.util.stream.*
All of needed packages or classes that are not listed above, can be imported like in normal Java class.
Did you forget an already defined variable? That’s not a problem! Just type:
jshell> /vars
| Stream<String> names = java.util.stream.ReferencePipeline$Head@6e1567f1
The same way you can list all of declared methods:
jshell> /methods
| void printStringStream(Stream<String>)
If you want close Jshell tool, just type:
jshell> /exit
| Goodbye
Default garbage collector
Oracle proposed to make G1 garbage collector (which was first introduced in Java 8) the default one from Java 9. Switching to G1 provides better overall experience than a throughput-oriented collectors such as the Parallel GC, which was the default one in prior Java versions.
Language changes in Java SE 9
Private methods in interfaces
Starting from Java 9, we can define private methods in interfaces.
Let’s say we have interface that returns number of available white and red items:
public interface ClientService {
default long getNumberOfWhiteItems(List<Item> items) {
return items.stream()
.filter(Item::isAvailable)
.filter(item -> item.getColor() == Color.WHITE)
.count();
}
default long getNumberOfRedItems(List<Item> items) {
return items.stream()
.filter(Item::isAvailable)
.filter(item -> item.getColor() == Color.RED)
.count();
}
}
We can extract common business logic to private methods and make them cleaner:
public interface ClientService {
private long getNumberOfAvailableItems(List<Item> items, Predicate<Item> filteringPredicate) {
return items.stream()
.filter(Item::isAvailable)
.filter(filteringPredicate)
.count();
}
default long getNumberOfWhiteItems(List<Item> items) {
return getNumberOfAvailableItems(items, item -> item.getColor() == Color.WHITE);
}
default long getNumberOfRedItems(List<Item> items) {
return getNumberOfAvailableItems(items, item -> item.getColor() == Color.RED);
}
}
Thanks to this we gain more flexibility in exposing only intended methods to API users and can avoid code duplication in default methods.
Optional Class
Java 9 comes with new methods in Optional class.
Optional.ifPresentOrElse()
Let’s assume that we have two methods to display information about shopping basket depending on its presence.
Optional<ShoppingBasket> shoppingBasket = findShoppingBasket();
Instead of writing traditional if/else construction
if (shoppingBasket.isPresent()) {
displayShoppingBasketContent(shoppingBasket.get());
} else {
displayEmptyShoppingBasket();
}
We can use ifPresentOrElse method:
shoppingBasket.ifPresentOrElse(this::displayShoppingBasketContent, this::displayEmptyShoppingBasket);
Optional.or()
Other new method available in Optional class is or. If value is present, method will return Optional describing the value, otherwise returns an Optional produced by the supplying function:
Optional<ShoppingBasket> shoppingBasket = findShoppingBasket().or(() -> Optional.of(new ShoppingBasket("empty shopping basket")));
Optional.stream()
Since Java 9 we can treat the Optional instance as a Stream and utilize all methods from Stream API. This makes it also much more convenient to work with streams of Optionals.
Immutable Collection Factory
Java 9 came with static methods on the List, Set and Map interfaces for creating unmodifiable instances of those collections. Till now, to create immutable collection, programmers had to construct it, store it in a local variable, fill with add method and wrap into a unmodifiable collection.
private Set<String> createImmutableSet() {
Set<String> names = new HashSet<>();
names.add("John");
names.add("George");
names.add("Betty");
return Collections.unmodifiableSet(names);
}
Now, you can replace it with:
private Set<String> createImmutableSet() {
return Set.of("John", "George", "Betty");
}
It’s also trivial to create an immutable map:
return Map.of("John", 1, "Betty", 2);
CompletableFuture improvements
The newest version of Java introduces several new methods to CompletableFuture class. Most significant one relates to timeouts.
or Timeout exceptionally completes a ComplatableFuture if it’s not completed in given time:
CompletableFuture<String> newOne = future.orTimeout(10, TimeUnit.SECONDS);
The other one is completeOnTimeout:
CompletableFuture<String> newOne = future.completeOnTimeout("value in case of timeout", 10, TimeUnit.SECONDS);
The method completes current CompletableFuture with “value in case of timeout” if not completed before the timeout.
Enhancements in @Deprecated
Java 9 provides enhancements for @Deprecated annotation by adding two new parameters to it:
since – defines version in which the annotated element became deprecated
forRemoval – indicates whether the annotated element is subject to removal in future version
@Deprecated(since = "4", forRemoval = true)
public String getDescription()
Java 10
Java 10 didn’t come with groundbreaking features, however, it was delivered as promised, only 6 months after Java 9 release and we need to commend that, because in the past years there were always problems with delivering promised Java updates on time.
Keyword “var” (Local-Variable Type Inference)
Probably the most recognisable feature of this release (at least from developer’s point of view). The var keyword that has been introduced can replace strict variable type declaration if the type may be easily inferred by the compiler. Therefore we can type less, don’t need to duplicate type information and it just makes the code look nicer.
We can use var in the context of local variables (instantly initialized), for loops and try-with-resources blocks.
We can’t use var e.g. when declaring class fields or method parameters.
A few examples of correct usage of var:
var company = "Codete"; // infers String
var characters = company.toCharArray(); // infers char[]
var numbers = List.of("a", "b", "c");
for (var nr : numbers) {
System.out.print(nr + " ");
}
And a few code samples with var which will not compile:
var foo;
var ints = {0, 1, 2};
var appendSpace = a -> a + " ";
private var getFoo() {
return "foo";
}
Also it’s important that the compiler will resolve the exact type of the object that a variable is initialized with. Therefore we will get a compilation error in the following situation:
var users = new ArrayList<User>(); // type resolved: ArrayList<User>
users = new LinkedList<User>(); // error
Additions to JDK
A few small additions came also to the standard class library. For instance, there is a new overloaded version of Optional.orElseThrow() which doesn’t take any parameters and throws NoSuchElementException by default.
Additionally, API for creating unmodifiable collections has been improved by adding List.copyOf(), Set.copyOf(), Map.copyOf() methods, which are factory methods for creating unmodifiable instances from existing collections. Also, Collectors class has some new methods like toUnmodifiableList, toUnmodifiableSet, toUnmodifiableMap.
Parallel Full GC for G1
As we mentioned before, G1 is the default GC starting from Java 9. It was mainly designed to avoid full collections and preventing the “stop the world” event. It increased the performance significantly, however, there was still probability that if concurrent collections couldn’t reclaim memory quickly enough, then classic full GC would be used as a fallback.
Therefore in Java 10 they took care of this particular situation too and improved the algorithm to parallelize the full GC.
Java 11
Local-Variable Syntax for Lambda Parameters
Currently when we want to specify lambda parameters types, we need to do this explicitly and can’t use var keyword introduced in Java 10.
IntFunction<Integer> doubleIt1 = (int x) -> x * 2; // Correct
IntFunction<Integer> doubleIt2 = (var x) -> x * 2; // Error
The second line won’t compile in Java 10, but will compile in Java 11.
But, hey, why do we need that at all? If we can write it like this:
IntFunction<Integer> doubleIt = x -> x * 2;
even in Java 8 and type inference will do the trick.
Yes, it’s true, but sometimes you have to use explicit typing in lambda and then var may be useful, e.g. when you want to make a parameter final or add annotations.
IntFunction<Integer> doubleIt1 = (@Valid final int x) -> x * 2; // Compiles since Java 8
IntFunction<Integer> doubleIt2 = (@Valid final var x) -> x * 2; // Will compile from Java 11
Launch Single-File Source-Code Programs
With that feature simple, single-file programs (which are common especially at early stages of learning Java) won’t need to be compiled separately. Typing simply
java SimpleProgram.java
will run the program immediately.
More than just features
Currently, list of planned features for Java 11 is quite small, but release is planned for September 2018 and perhaps some extra features will be added up to that time.
However, these are not fancy features what is going to make Java 11 release so important, but the fact that this version will be the LTS version and thus it will be the most reliable substitute for popular Java 8.
Conclusion
The change of Java release cycle, many syntax-sugar features that came in Java 9 & 10, plenty of safety & performance improvements and the approaching Java 11 platform long term support bring the conclusion that Oracle has a vision for adopting innovation to the language and maintains high level of stability at the same time. This all makes Java development even more interesting and we’re sure that there are more great news coming our way.
This article presented a subset of features introduced to Java between versions 9 and 11, which in our subjective vision are the most interesting and useful ones from Java developer’s perspective. Hope you enjoyed it.
Keywords:
Java 9, JDK 9, Java 10, JDK 10, Java 11, JDK 11, var, local-variable, Jigsaw, modularity, Jshell, REPL, GC, G1, Garbage Collector, Private method, Interfaces, Immutable, collections, List, Set, Map, CompletableFuture, timeout, deprecated
Sources:
http://openjdk.java.net
http://www.journaldev.com/13106/javase9-module-system-part1
https://blogs.oracle.com/sundararajan/entry/playing_with_java_java9_repl
http://www.baeldung.com/new-java-9
https://bentolor.github.io/java9-in-action/#/5/1
https://blog.takipi.com/java-11-will-include-more-than-just-features/
Java Optionals as return objects
https://dzone.com/articles/java-8-optional-usage-and-best-practices
According to the Oracle documentation, an Optional is a container object that may or may not contain a non-null value. It was introduced in Java 8 to cure the curse of NullPointerExceptions. In essence, Optional is a wrapper class that contains a reference to some other object. In this context, an object is just a pointer to a memory location and it can as well point to nothing. Another way to look at it is as a way to provide a type-level solution for representing optional values instead of null references.
Life Before Optional
Before Java 8, programmers would return null instead of Optional. There were a few shortcomings with this approach. One was that there wasn’t a clear way to express that null might be a special value. By contrast, returning an Optional is a clear statement in the API that there might not be a value in there. If we wanted to make sure that we won't get a null pointer exception, then we would need to do explicit null check for each reference, as shown below, and we all agree that’s a lot of boilerplate.
// Life before Optional
private void getIsoCode( User user){
if (user != null) {
Address address = user.getAddress();
if (address != null) {
Country country = address.getCountry();
if (country != null) {
String isocode = country.getIsocode();
if (isocode != null) {
isocode = isocode.toUpperCase();
}
}
}
}
}
To ease this process, let’s take a look at how we can use the Optional class instead, from creating and verifying an instance to using the different methods it provides and combining it with other methods that return the same type, the latter being where the true power of Optional lies.
Features of Optional
The optional class provides around 10 methods, which we can use for creating and using the Optional class and we are going to see how they are used below.
Creating an Optional
The are three creational methods for creating an optional instance.
1. static <T> Optional<T> empty()
Returns an empty Optional instance.
// Creating an empty optional
Optional<String> empty = Optional.empty();
Returns an empty {Optional} instance. No value is present for this Optional. Though, it may be tempting to do so, avoid testing if an object is empty by comparing with {==} against instances returned by Option.empty(). There is no guarantee that it is a singleton. Instead, use isPresent().
2. static <T> Optional<T> of(T value)
Returns an Optional with the specified present non-null value.
// Creating an optional using of
String name = "java";
Optional<String> opt = Optional.of(name);
The static method of expects a non-null argument; otherwise, it will throw a nullpointer exception. So, what if we don't know if the argument will be null or not, that's when we use ofNullable, which is described below.
3. static <T> Optional<T> ofNullable(T value)
Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.
// Possible null value
Optional<String> optional = Optional.ofNullable(name());
private String name(){
String name = "Java";
return (name.length() > 5) ? name : null;
}
By doing this, if we pass in a null reference, it doesn’t throw an exception but rather returns an empty Optional object:
So, those are the three methods of creating Optionals either dynamically or manually. The next set of methods is for checking value presence.
1. boolean isPresent()
Return true if there is a value present; otherwise, it's false. Meaning to returns true if the contained object is not null and false otherwise. This method is normally called first on an Optional before doing any other operations on the object.
//ispresent
Optional<String> optional1 = Optional.of("javaone");
if (optional1.isPresent()){
//Do something, normally a get
}
2. boolean isEmpty()
Return false if there is a value present; otherwise, it's true. This does the opposite of isPresent and is only available in Java 11 and above.
//isempty
Optional<String> optional1 = Optional.of("javaone");
if (optional1.isEmpty()){
//Do something
}
3. void ifPresent(Consumer<? super T> consumer)
If a value is present, invoke the specified consumer with the value; otherwise, do nothing.
If you are new to Java 8, then you are probably wondering: What is a consumer? Well, in simple terms, a consumer is a method that accepts an argument and does not return anything. When using ifPresent, this looks like killing two birds with one stone. We can do a value presence check and perform the intended operation with one method, as shown below.
//ifpresent
Optional<String> optional1 = Optional.of("javaone");
optional1.ifPresent(s -> System.out.println(s.length()));
The optional class provides another set of methods for getting a value in an Optional.
1. Tget()
If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException. After all is said and done, what we want is the value that is stored in the Optional, and we can get it by simply calling get(). However, this method throws an exception when the value is null; that's when the orElse() method comes to the rescue.
//get
Optional<String> optional1 = Optional.of("javaone");
if (optional1.isPresent()){
String value = optional1.get();
}
2. TorElse(Tother)
Return the value if present; otherwise, return other.
The orElse() method is used to retrieve the value wrapped inside an Optional instance. It takes one parameter that acts as a default value. The orElse() method returns the wrapped value if it’s present and its argument, otherwise:
//orElse
String nullName = null;
String name = Optional.ofNullable(nullName).orElse("default_name");
As if that is not enough, the Optional class goes on to provide another method of getting a value even if its null called orElseGet().
3. TorElseGet(Supplier<? extends T> other)
Return the value if present; otherwise, invoke other and return the result of that invocation.
The orElseGet() method is similar to orElse(). However, instead of taking a value return if the Optional value is not present, it takes a supplier functional interface, which is invoked and returns the value of the invocation:
//orElseGet
String name = Optional.ofNullable(nullName).orElseGet(() -> "john");
So, what is the difference between orElse() and orElseGet().
At first glance, it might seem as if the two methods have the same effect. However, this is not exactly the case. Let’s create some examples that highlight the similarity as well as the difference in behavior between the two.
First, let’s see how they behave when an object is empty:
String text = null;
String defaultText = Optional.ofNullable(text).orElseGet(this::getDefaultValue);
defaultText = Optional.ofNullable(text).orElse(getDefaultValue());
public String getDefaultValue() {
System.out.println("Getting Default Value");
return "Default Value";
}
In the above example, we wrap a null text inside an Optional object and we attempt to get the wrapped value using each of the two approaches. The side effect is as below:
Getting default value...
Getting default value...
The default method is called in each case. It so happens that when the wrapped value is not present, then both orElse() and orElseGet() work exactly the same way.
Now, let’s run another test where the value is present, and ideally, the default value should not even be created:
In this simple example, there is no significant cost to creating a default object, as the JVM knows how to deal with such. However, when a method such as default has to make a web service call or even query a database, then the cost becomes very obvious.
Best Practices for Using Optional
Just like any other feature of a programming language, it can be used correctly or it can be abused. In order to know the best way to use the Optional class, one needs to understand the following:
1. What it Is Trying to Solve
Optional is an attempt to reduce the number of null pointer exceptions in Java systems, by adding the possibility to build more expressive APIs that account for the possibility that sometimes return values are missing.
If Optional was there since the beginning, most libraries and applications would likely deal better with missing return values, reducing the number of null pointer exceptions and the overall number of bugs in general.
2. What it IS Not Trying to Solve
Optional is not meant to be a mechanism to avoid all types of null pointers. The mandatory input parameters of methods and constructors still have to be tested for example.
Like when using null, Optional does not help with conveying the meaning of an absent value. In a similar way, null can mean many different things (value not found, etc.), so can an absent Optional value.
The caller of the method will still have to check the javadoc of the method for understanding the meaning of the absent Optional, in order to deal with it properly.
Also, in a similar way that a checked exception can be caught in an empty block, nothing prevents the caller of calling get() and moving on.
3. When to Use It
The intended use of Optional is mainly as a return type. After obtaining an instance of this type, you can extract the value if it’s present or provide an alternate behavior if it’s not.
One very useful use case of the Optional class is combining it with streams or other methods that return an Optional value to build fluent APIs. See code snippet below
User user = users.stream().findFirst().orElse(new User("default", "1234"));
4. When Not to Use It
a) Do not use it as a field in a class as it is not serializable
If you do need to serialize an object that contains an Optional value, the Jackson library provides support for treating Optionals as ordinary objects. What this means is that Jackson treats empty objects as null and objects with a value as fields containing that value. This functionality can be found in the jackson-modules-java8 project.
b) Do not use it as a parameter for constructors and methods as it would lead to unnecessarily complicated code.
User user = new User("john@gmail.com", "1234", Optional.empty());
JDK 14
https://docs.oracle.com/en/java/javase/14/
https://docs.oracle.com/en/java/javase/14/docs/api/overview-summary.html
https://www.oracle.com/technetwork/java/javase/14-relnote-issues-5809570.html#NewFeature
Java Records ( JDK 14 )
https://www.infoq.com/articles/java-14-feature-spotlight/
java-14-records-infoq.com-Java 14 Feature Spotlight Records.pdf
- Java SE 14 (March 2020) introduces records as a preview feature. Records aim to enhance the language's ability to model "plain data" aggregates with less ceremony.
- A record can be best thought of as a nominal tuple; it is a transparent, shallowly immutable carrier for a specific ordered sequence of elements.
- Records can be used in a wide variety of situations to model common use cases, such as multiple return, stream joins, compound keys, tree nodes, DTOs, and more, and provide stronger semantic guarantees that allow developers and frameworks to more reliably reason about their state.
- Like enums, records come with some restrictions compared to classes, and so will not replace all data-carrier classes. Specifically, they are not intended as a replacement for mutable JavaBean classes.
- Existing classes that would qualify to be records can be compatibly migrated to records.
We can declare a simple x-y point abstraction as follows:
record Point(int x, int y) { }
which will declare a final class called Point, with immutable components for x and y and appropriate accessors, constructors, equals, hashCode, and toString implementations.
We are all familiar with the alternative - writing (or having the IDE generate) boilerplate-filled implementations of constructors, Object methods, and accessors.
These are surely cumbersome to write, but more importantly, they are more work to read; we have to read through all the boilerplate code just to conclude that we didn't actually need to read it at all.
Pros and Cons of records
As mentioned earlier, records come with some restrictions. Their instance fields (which correspond to the components declared in the record header) are implicitly final; they cannot have any other instance fields; the record class itself cannot extend other classes; and record classes are implicitly final. Other than that, they can have pretty much everything other classes can: constructors, methods, static fields, type variables, interfaces, etc.
In exchange for these restrictions, records automatically acquire implicit implementations of the canonical constructor (the one whose signature matches the state description), read accessors for each state component (whose names are the same as the component),
Java Record concepts
java-record-concepts-2020-cr.openjdk.java-Data Classes and Sealed Types for Java.pdf
Java - Use Loom or Reactive Programming
https://www.reddit.com/r/java/comments/nsmxt3/is_java_worth_learning_in_2021/
Loom - faster concurrency without functional loss
Java is Popular and Improving in 2021
https://redmonk.com/sogrady/2021/08/05/language-rankings-6-21/
Java will stay relevant in the forseeable future. Lots of awesome work is going on under various OpenJDK projects to improve Java.
Project Loom is working on making it easier to leverage concurrency through virtual threads etc. This will make writing server side applications which are already a Java stronghold easier.
Project Valhalla is working on bringing value based classes (aka user defined primitives) to Java and the JVM.
Project Panama is working on making interop with native libraries and memories simpler. It will also introduce the Vector API to help developers leverage SIMD.
Together, Valhalla and Panama will make Java even more relevant for big data, machine learning and artificial intelligence.
Project Amber is working on bringing new language features (prominently pattern matching) to Java,
There are also ongoing projects like Lilliput which aim to improve the JVM and as a result as languages running on the JVM.
JEXL - Java Expression Language for Scripting
https://commons.apache.org/proper/commons-jexl/
JEXL is a library intended to facilitate the implementation of dynamic and scripting features in applications and frameworks written in Java.
JEXL implements an Expression Language based on some extensions to the JSTL Expression Language supporting most of the constructs seen in shell-script or ECMAScript.
Its goal is to expose scripting features usable by technical operatives or consultants working with enterprise platforms.
The library exposes a small footprint API - the core features fit in 3 classes and 10 methods - that can be used in various conditions:
- Scripting features:
- Your application lets (advanced) users evaluate or define some simple expressions like computation formulas.
- Module or component configuration:
- Your application has configuration files (eventually generated by a design module) consumed by the end-user module that would benefit from variables and expressions.
- When it would be convenient to use IOC but overall complexity doesn't require (or can't depend upon) a full-blown library (Spring, Guice...).
- Loose-coupling of interfaces and implementations or duck-typing:
- You have optional classes that your code cant consider as compilation dependencies.
- You have to integrate and call "legacy" code or use components that you dont want to strongly depend upon.
- Simple template capabilities:
- Your application has basic template requirements and JSPs or Velocity would be overkill or too inconvenient to deploy.
JEXL name stands for Java EXpression Language, a simple expression language originally inspired by Apache Velocity and the Expression Language defined in the JavaServer Pages Standard Tag Library version 1.1 (JSTL) and JavaServer Pages version 2.0 (JSP). JEXL 2.0 added features inspired by Unified EL. The syntax is now close to a mix of ECMAScript and "shell-script" making it easy to master by technical operatives or consultants. The objects exposed and their behavior obviously need to be documented though...
The API and the expression language exploit Java-beans naming patterns through introspection to expose property getters and setters. It also considers public class fields as properties and allows to invoke any accessible method.
JEXL attempts to bring some of the lessons learned by the Velocity community about expression languages in templating to a wider audience. Commons Jelly needed Velocity-ish method access, it just had to have it.
It must be noted that JEXL is not a compatible implementation of EL as defined in JSTL 1.1 (JSR-052) or JSP 2.0 (JSR-152). For a compatible implementation of these specifications, see the Commons EL project.
// Create or retrieve an engine
JexlEngine jexl = new JexlBuilder().create();
// Create an expression
String jexlExp = "foo.innerFoo.bar()";
JexlExpression e = jexl.createExpression( jexlExp );
// Create a context and add data
JexlContext jc = new MapContext();
jc.set("foo", new Foo() );
// Now evaluate the expression, getting the result
Object o = e.evaluate(jc);
Potential Value Opportunities
Java still very popular in 2021 - consider the easy way with Groovy
Potential Challenges
GO vs Java - which is better?
For what purpose ??
GO vs Java on a recursive loop test
https://medium.com/p/e6f29ad65293/responses/show
java-vs-go-t1-medium.com-A Simple Performance Test and Difference Go vs Java.pdf
response
Thanks for an unrealistic benchmark. Wish it were this simple. Details on which versions of both programs were run would have been helpful. This is an old argument. A compiled program will run faster than one executing on a VM. So the theory goes. The same was said the C was faster than Smalltalk ( which also was VM based ). In reality, when we built apps using both, Smalltalk was faster more than C apps 80% of the time. Why? Because the language constructs simplified coding dramatically over C and its libraries. And, like any good VM language, you cheat and use native libraries as needed as well as compiled code optimizations in the VM runtime. The biggest differences in performance relate to design, I/O and memory optimizations — none of which are in this benchmark. Many times, recommending a compiled language over a VM language for a benchmark like this will actually cost the company more money in the long run.
You can statically compile Java or Groovy and run it on Graal VM for speed.
Java Decompile bytecode to source
https://www.javacodegeeks.com/2021/11/13-best-java-decompilers-for-download-and-online-use-for-java-developers.html
Consider IntelliJ which includes a Java decompiler
Procyon - java decompiler
https://github.com/mstrobel/procyon
Procyon is a suite of Java metaprogramming tools focused on code generation and analysis. It includes the following libraries:
- Core Framework
- Reflection Framework
- Expressions Framework
- Compiler Toolset (Experimental)
- Java Decompiler (Experimental)
The Procyon libraries are available from Maven Central under group ID org.bitbucket.mstrobel
.
Core Framework
The procyon-core
framework contains common support classes used by the other Procyon APIs. Its facilities include string manipulation, collection extensions, filesystem/path utilities, freezable objects and collections, attached data stores, and some runtime type helpers.
Reflection Framework
The procyon-reflection
framework provides a rich reflection and code generation API with full support for generics, wildcards, and other high-level Java type concepts. It is based on .NET's System.Reflection
and System.Reflection.Emit
APIs and is meant to address many of the shortcomings of the core Java reflection API, which offers rather limited and cumbersome support for generic type inspection. Its code generation facilities include a TypeBuilder
, MethodBuilder
, and a bytecode emitter.
For more information, see the Reflection Framework topic.
Example
final Type<Map> map = Type.of(Map.class);
final Type<?> rawMap = map.getErasedType();
final Type<Map<String, Integer>> boundMap = map.makeGenericType(Types.String, Types.Integer);
System.out.println(map.getDeclaredMethods().get(1));
System.out.println(rawMap.getDeclaredMethods().get(1));
System.out.println(boundMap.getDeclaredMethods().get(1));
System.out.println(boundMap.getGenericTypeParameters());
System.out.println(boundMap.getTypeArguments());
Output
public abstract V put(K, V)
public abstract Object put(Object, Object)
public abstract Integer put(String, Integer)
[K, V]
[java.lang.String, java.lang.Integer]
JD project - java decompiler ( up to JDK 10x )
https://java-decompiler.github.io/
The “Java Decompiler project” aims to develop tools in order to decompile and analyze Java 5 “byte code” and the later versions.
JD-GUI is a standalone graphical utility that displays Java source codes of “.class” files. You can browse the reconstructed source code with the JD-GUI for instant access to methods and fields.
JD-Eclipse is a plug-in for the Eclipse platform. It allows you to display all the Java sources during your debugging process, even if you do not have them all.
JD-Core is a library that reconstructs Java source code from one or more “.class” files. JD-Core may be used to recover lost source code and explore the source of Java runtime libraries. New features of Java 5, such as annotations, generics or type “enum”, are supported. JD-GUI and JD-Eclipse include JD-Core library.
JD-Core, JD-GUI & JD-Eclipse are open source projects released under the GPLv3 License.
create jar or zip to use JD-GUI
https://stackoverflow.com/questions/1384619/batch-decompiling-of-java-files-with-jd-gui
Command line decompilation for JD-GUI is a highly requested feature but it's not implemented yet. Perhaps you can use the following workaround in the meantime:
- jar (or zip) all the classes you want decompiled together.
- Launch JD-GUI and open your jar (zip) archive.
- Use "File" - "Save JAR Sources" menu option.
- It will decompile all classes from your archive and save their sources into another zip file.
Candidate Solutions
Open-source JDBC Connectors - java app access to many data sources
SourceForge - free JDBC drivers
https://sourceforge.net/directory/?q=jdbc%20driver
SQLite driver
https://sourceforge.net/projects/sqlite-jdbc-driver.mirror/
sharepoint eos driver ?
https://sourceforge.net/directory/?q=sharepoint%20jdbc%20driver
AWS Document Db driver
https://sourceforge.net/projects/amz-docdb-jdbc-driver.mirror/
CSV file jdbc driver
https://sourceforge.net/projects/csvjdbc/
DB apps test driver
https://sourceforge.net/projects/dbdatestdriver/
CouchDB connector for SQLite jdbc driver
Hi Jim,
Unfortunately I haven't had the opportunity to work with this project in ages. I'm sure something would have to be updated to get it working. Though most likely those changes are small.
If you've got time to give it a try and help identify what needs to be updated I'd be happy to see the project updated & can help shepherd that process. But as I don't use this in my day job I can't promise to be super responsive.
Either way thanks for reaching out, I had a lot of fun working with couchdb and enjoy revisiting this tech.
On Mon, Jul 17, 2023, at 09:48, Jim Mason wrote:
Hi Jeff
I found your sqlite / couchdb connector
Does it work with current versions of those products?
Thanks
Jim Mason
OWASP Web Security project
https://www.owasp.org/index.php/Main_Page
Eclipse
Free Java Eclipse Tutorial on Udemy
https://www.udemy.com/course/eclipse-java-tutorial-for-beginners
IntelliJ
VSCode
Maven
https://maven.apache.org/users/index.html
This documentation centre is for those that have decided to use Maven to build their project, and would like to get started quickly, or are already using Maven and would like to add new functionality or fix a problem in their build.
Reference
The Maven Toolchains provide a way for plugins to discover what JDK (or other tools) are to be used during the build, without the need to configure them in each plugin nor in every pom.xml
, or forcing a precise location among every machine building the project.
With Maven Toolchains applied to JDK toolchain, a project can now be built using a specific version of JDK independent from the one Maven is running with. Think how JDK versions can be set in IDEs like IDEA, NetBeans and Eclipse, or how you can compile with an older JDK from Maven running with a recent one.
Gradle
https://www.infoq.com/news/2022/12/eclipse-migration-toolkit-java/
Adoptium has introduced the Eclipse Migration Toolkit for Java (EMT4J), an open source Eclipse project capable of analyzing and upgrading applications from Java 8 to Java 11 and from Java 11 to Java 17. EMT4J will support upgrading to future LTS versions.
Organizations advise keeping the Java runtime up-to-date to get security and functional improvements. In the meantime, Long Term Support (LTS) Java versions will be released every two years and projects such as Spring Framework 6 now require Java 17. Unfortunately, adoption of new Java versions is relatively slow. For example, in 2022, four years after its release, Java 11 was used by less than 49 percent of the Java applications
EMT4J offers a Maven plugin (not yet available on Maven central), Java agent and command-line solution to analyze project incompatibilities with new Java versions and the output is written as TXT
, JSON
or HTML
formats.
This analyzes the class files in the specified directory and displays potential issues when upgrading from Java 8 to Java 17 in the java8to17.html file. Alternatively the .bat
or .sh
scripts in the bin directory of the extracted archive may be used to start the command line analysis. The README file describes all available options for analyzing classes and JAR
files
Tiny MCE embedded HTML editor
https://staymanhou.github.io/tinymce-coding-cheat-sheet/index.html
https://www.tiny.cloud/blog/category/how-tos-and-tutorials/
https://www.tiny.cloud/
Step-by-step guide for Example
sample code block
Recommended Next Steps
Related articles