Monday, October 30, 2023

Exploring Java EE 7: Unveiling the Power of Enterprise Edition

Exploring Java EE 7: Unveiling the Power of Enterprise Edition

In the ever-evolving world of technology, Java EE 7 stands as a robust pillar in the realm of enterprise software development. In this comprehensive article, we delve into the intricate details and features of Java EE 7, aiming to provide you with a profound understanding of this groundbreaking technology.

What is Java EE 7?


Java EE, or Java Platform, Enterprise Edition, is a set of specifications that extend the Java SE (Standard Edition) with specifications for enterprise features such as distributed computing and web services. Java EE 7, released in 2013, represents a significant milestone in the world of enterprise software development. It's a platform designed to simplify the creation of large-scale, distributed, and multi-tiered enterprise applications.

A Revolutionary Step Forward


Java EE 7 brought about a multitude of innovations that revolutionized the way developers design, build, and deploy enterprise applications. Let's take a closer look at some of the key features and benefits that make Java EE 7 a game-changer:

1. API Enhancements

One of the highlights of Java EE 7 is the enhancement of various APIs. This improvement is particularly noticeable in the Contexts and Dependency Injection (CDI) API, which simplifies the development of Java EE applications. Additionally, the Java API for WebSocket simplifies the integration of real-time communication in web applications.

2. Concurrency Utilities

Java EE 7 introduced a standardized API for managing concurrency, making it easier to handle complex, multi-threaded applications. The ManagedExecutorService and ManagedScheduledExecutorService APIs offer fine-grained control over concurrent tasks, improving performance and resource management.

3. Batch Applications

Another exciting addition is the Batch Applications API. It streamlines the development of batch processing applications, enabling the efficient execution of large-scale, long-running tasks. This is invaluable for applications that require the processing of massive amounts of data.

4. Simplified Security

Java EE 7 enhances security features by simplifying the way developers implement authentication and authorization mechanisms. This, in turn, ensures that your enterprise applications are more secure than ever.

5. JSON Processing API

The introduction of a JSON Processing API simplifies the manipulation of JSON data. JSON has become the preferred format for data exchange in web applications, and this API makes it easier than ever to work with JSON data.

Enterprise-Ready Features


Java EE 7 is designed with the enterprise in mind, and as such, it provides several features that cater to the unique demands of large-scale applications:

1. Scalability

The platform offers a high degree of scalability, allowing applications to expand seamlessly as your enterprise grows. Whether you're running a small business or a multinational corporation, Java EE 7 can handle your demands.

2. Portability

One of the key strengths of Java EE 7 is its portability. Applications built on this platform can run on various Java EE-compatible servers, ensuring flexibility in deployment.

3. Developer Productivity

Java EE 7 simplifies the development process, reducing the time and effort required to create enterprise applications. This not only boosts productivity but also cuts development costs.

4. Interoperability

Thanks to its extensive set of APIs, Java EE 7 ensures seamless interoperability with other systems and technologies. This is vital for integrating diverse components within an enterprise architecture.

Real-World Applications


To truly understand the significance of Java EE 7, it's essential to examine its real-world applications. Countless industries and organizations benefit from the power of this enterprise edition, and here are a few examples:

1. Finance Sector

In the finance sector, where data accuracy and security are paramount, Java EE 7 is instrumental in building robust and scalable applications for online banking, trading platforms, and risk management systems.

2. E-commerce

E-commerce platforms rely on Java EE 7 to provide a seamless shopping experience, handling large numbers of transactions, user interactions, and inventory management efficiently.

3. Healthcare

Healthcare institutions leverage Java EE 7 for building electronic health record (EHR) systems, ensuring the confidentiality and accessibility of patient data.

4. Manufacturing

Manufacturing companies utilize Java EE 7 to streamline their supply chain management, quality control, and production planning processes.

Conclusion

In the dynamic world of enterprise software development, Java EE 7 has emerged as a powerhouse. With its advanced APIs, scalability, and developer-friendly features, it empowers businesses across various sectors to create cutting-edge, high-performance applications. By embracing Java EE 7, you're not just adopting a technology; you're embarking on a journey toward excellence in enterprise software development.

Friday, October 27, 2023

Exploring the Versatility of JavaFX

Exploring the Versatility of JavaFX

JavaFX is a versatile and dynamic platform that has revolutionized the world of software development. With its remarkable features and capabilities, it has become an indispensable tool for developers worldwide. In this article, we will delve into the key features of JavaFX that make it a powerful choice for creating cutting-edge applications.

Introducing JavaFX: A Brief Overview


JavaFX is a rich set of graphics and media APIs that provide endless possibilities for creating interactive and visually stunning applications. It is a part of the Java Development Kit (JDK), making it readily accessible for Java developers. Let's explore the exceptional features that set JavaFX apart.

1. Rich User Interface (UI)

JavaFX is renowned for its ability to create captivating user interfaces. Its comprehensive library of UI components allows developers to craft modern and aesthetically pleasing interfaces, enhancing the user experience. From stylish buttons to intricate animations, JavaFX offers a wide range of tools to bring your application to life.

2. Cross-Platform Compatibility

One of JavaFX's standout features is its cross-platform compatibility. Developers can create applications that run seamlessly on various operating systems, including Windows, macOS, and Linux. This versatility saves time and effort, as there's no need to develop separate versions for different platforms.

3. Scene Builder

JavaFX simplifies the UI design process with its Scene Builder tool. This intuitive WYSIWYG editor enables developers to create UI layouts effortlessly by simply dragging and dropping components. It streamlines the development process, reducing the need for extensive coding.

4. Rich Set of Controls

JavaFX provides an extensive array of controls that cater to different application needs. Whether you require tables, charts, or sophisticated text editing, JavaFX has you covered. This versatility allows developers to create diverse applications without the need for third-party libraries.

5. 2D and 3D Graphics

For applications that demand intricate graphics and animations, JavaFX's support for 2D and 3D graphics is invaluable. It allows developers to craft visually engaging applications that stand out in today's competitive market.

6. Built-In Animation

Creating interactive and engaging animations is a breeze with JavaFX. It offers built-in animation support, enabling developers to add motion and visual appeal to their applications without the complexities of external animation libraries.

7. Webview Integration

JavaFX seamlessly integrates web content into applications through its WebView component. This feature is particularly useful for embedding web pages or web-based content within your JavaFX application, expanding its capabilities.

8. Hardware Acceleration

JavaFX harnesses the power of hardware acceleration to optimize the performance of graphics-intensive applications. This results in smoother animations and an overall enhanced user experience.

9. Extensive Documentation

JavaFX boasts a wealth of documentation and a robust community of developers. This means that if you ever run into issues or need guidance, you can easily find the support and resources necessary to overcome any obstacles.

10. Active Development

Oracle actively maintains and develops JavaFX, ensuring that it remains up-to-date and continues to evolve with the changing landscape of technology. This commitment to improvement makes JavaFX a reliable choice for long-term development projects.

In conclusion, JavaFX is a powerhouse in the world of software development. Its feature-rich environment, cross-platform compatibility, and user-friendly tools make it an ideal choice for developers aiming to create exceptional applications. Whether you are developing a business application, a game, or a multimedia-rich project, JavaFX has the capabilities to bring your vision to life. Embrace the possibilities of JavaFX and unlock the potential for creating groundbreaking software applications.

Wednesday, October 25, 2023

Java vs. Oracle: Deciphering the Battle of Titans

Java, Oracle, Oracle Java, Oracle Java Career, Oracle Java Skills, Oracle Java Jobs, Oracle Java Prep, Oracle Java Preparation, Oracle Java Tutorial and Materials

In the ever-evolving world of technology, the comparison between Java and Oracle is a hot topic. Both are powerhouse solutions, each with its own set of unique strengths and applications. In this comprehensive guide, we'll dive deep into the realm of Java and Oracle, dissecting their capabilities, use cases, and advantages to help you make an informed decision.

The Java Odyssey


Java is an open-source, versatile programming language that has left an indelible mark on the tech world. Created by Sun Microsystems (now owned by Oracle Corporation), Java is celebrated for its platform independence. This means you can write code once and run it on multiple platforms without modification, making it a preferred choice for developers.

Key Advantages of Java


1. Platform Independence: As previously mentioned, this is Java's crowning glory. It's compatible with various operating systems, including Windows, macOS, and Linux, which greatly eases the development process.

2. Robust and Secure: Java's strong memory management, automatic garbage collection, and extensive security features make it a dependable choice for mission-critical applications.

3. Vast Community Support: With a massive developer community, Java boasts a wealth of resources, libraries, and frameworks. If you have a question, someone out there has an answer.

4. Scalability: Whether you're working on a small project or a colossal enterprise-level application, Java can handle it all. Its scalability is second to none.

Common Use Cases for Java


◉ Web Development: Popular web frameworks like Spring and JavaServer Faces (JSF) make Java an excellent choice for building web applications.

◉ Android App Development: Java is the official language for Android app development, making it indispensable for mobile developers.

◉ Big Data Processing: Hadoop, an open-source big data framework, is built on Java, demonstrating its prowess in handling vast amounts of data.

The Oracle Enigma


Oracle, on the other hand, is renowned for its prowess in the database management domain. It's a juggernaut in the world of relational database systems. Oracle Corporation, the brains behind this technology, has created a suite of tools and technologies that cater to the demands of businesses and enterprises worldwide.

Key Advantages of Oracle


1. High Performance: Oracle databases are known for their lightning-fast performance. They can efficiently manage large datasets, making them ideal for businesses with substantial data needs.

2. Data Security: Oracle places a significant emphasis on data security. It offers various features to protect your data from unauthorized access or malicious attacks.

3. Scalability: Just like Java, Oracle databases are highly scalable, accommodating the growth of your business without a hitch.

4. Comprehensive Ecosystem: Oracle provides a wide range of products and services, including cloud solutions, making it a one-stop-shop for all your database and data management needs.

Common Use Cases for Oracle


◉ Enterprise Database Management: Oracle databases are the go-to choice for businesses and organizations with extensive data management requirements.

◉ Data Warehousing: The ability to handle and analyze massive datasets makes Oracle the prime choice for data warehousing.

◉ Cloud Solutions: Oracle's cloud services offer scalable, secure, and high-performance options for businesses migrating to the cloud.

The Face-Off


Now that we've examined the individual strengths of Java and Oracle, it's time to pit them against each other.

Performance

In the performance arena, Oracle holds a slight edge due to its dedicated focus on database management. It's finely tuned for handling data, providing blazing-fast data retrieval and processing. However, Java can be optimized for various applications, so performance can vary based on the specific use case.

Versatility

Java takes the lead in versatility. Its ability to function across diverse platforms and applications is unmatched. Oracle, while versatile in its own right, excels primarily in database management.

Security

Both Java and Oracle place a strong emphasis on security, but Oracle's database security features give it a slight advantage in this department.

Scalability

Here, it's a tie. Both Java and Oracle are highly scalable, ensuring they can grow with your business.

Which One Should You Choose?


The choice between Java and Oracle ultimately depends on your specific needs and objectives. If you're developing a web application, mobile app, or working in a diverse tech environment, Java is the natural choice. On the other hand, if your primary concern is managing and securing data, then Oracle should be your top pick.

It's essential to evaluate your project's requirements and consult with experts to make an informed decision. While you can't go wrong with either choice, selecting the one that aligns best with your goals is crucial.

In conclusion, the battle of Java vs. Oracle is not about one being better than the other; it's about which one suits your requirements. Each has its unique strengths, and both are integral components of the ever-expanding tech landscape.

Monday, October 23, 2023

Unveiling Java 21: The Future of Programming

Unveiling Java 21, Core Java, Java Prep, Java Preparation, Java Guides, Oracle Java Certification

In the dynamic realm of programming, the emergence of new versions and technologies is a frequent occurrence, making it essential for software developers and enthusiasts to stay updated. Java, a stalwart in the programming world, has recently unveiled its latest iteration - Java 21. This article delves into the exciting features and improvements that Java 21 brings to the table, equipping you with the knowledge to stay at the forefront of the programming landscape.

Understanding Java 21


Java, known for its versatility, portability, and reliability, has undergone a significant transformation in its latest release. Java 21 promises to further enhance these characteristics while introducing various novel elements to make it an even more powerful tool in the hands of developers.

1. Enhanced Performance

Java 21 is designed to be faster and more efficient than its predecessors. With optimized execution, this version reduces startup times and accelerates the execution of code. The improved performance ensures that Java remains a top choice for both small-scale applications and large-scale enterprise systems.

2. Records and Pattern Matching

One of the standout features of Java 21 is the introduction of Records and Pattern Matching. Records simplify the creation of immutable classes, streamlining the process of defining data-centric classes. Pattern Matching, on the other hand, enhances the readability and expressiveness of your code by allowing concise conditional statements.

3. Project Loom

Java 21 brings Project Loom to the forefront, a significant development that aims to simplify concurrency. With Loom, you can write concurrent code that is more readable and maintainable, making it easier to work with threads and asynchronous programming.

4. Foreign Function & Memory API

To keep pace with modern programming trends, Java 21 introduces the Foreign Function & Memory API, allowing seamless interaction with native code and memory. This feature empowers developers to access and utilize external libraries with ease.

5. Pattern Matching for instanceof

Pattern Matching for instanceof is another exciting addition. It simplifies type checking and casting by introducing a concise and intuitive syntax. This enhancement fosters clean and robust code practices.

6. Deprecation and Removal of Older Features

Java 21 takes a step forward by deprecating and removing outdated features. This ensures that the language remains concise and relevant, and it encourages developers to embrace modern and more efficient programming practices.

How Can Java 21 Benefit You?


With Java 21, developers, both seasoned and newcomers, can benefit immensely. Here are some of the advantages you can expect:

1. Improved Productivity

The enhanced features in Java 21 lead to increased productivity. Writing code becomes more intuitive and efficient, reducing the time and effort required to develop software.

2. Enhanced Code Quality

Java 21 encourages best practices and clean coding. The introduction of Records, Pattern Matching, and other features helps developers write more robust and less error-prone code.

3. Competitive Edge

Staying updated with the latest programming languages and features is essential in a rapidly evolving field. By mastering Java 21, you gain a competitive edge in the job market and software development landscape.

Transitioning to Java 21


If you're already using Java in your projects, transitioning to Java 21 is a logical step. However, it's essential to understand that some older features may be deprecated, and you may need to refactor your code accordingly. The effort is worthwhile, as the benefits of Java 21 are substantial.

For newcomers to Java, Java 21 is a fantastic place to start. You'll be learning the latest version, which means you'll be equipped with the most up-to-date skills in the Java ecosystem.

Friday, October 20, 2023

Unleashing the Power of Oracle Java

Unleashing the Power of Oracle Java: A Comprehensive Guide

In the ever-evolving world of technology, Oracle Java stands as an indispensable platform that has shaped the way we develop and run applications. In this comprehensive guide, we delve deep into the world of Oracle Java, exploring its significance, applications, and why it remains a pivotal player in the realm of programming languages and platforms.

The Genesis of Oracle Java


Oracle Java, often simply referred to as Java, is a robust, versatile, and object-oriented programming language and platform that was first introduced by Sun Microsystems in 1995. Since then, it has undergone significant advancements under Oracle Corporation, solidifying its position as a preferred choice for developers across the globe.

The Versatility of Java


Java's Role in Web Development

One of Java's primary applications is in web development. Its ability to create dynamic, interactive, and secure web applications has made it a go-to choice for web developers. Java's compatibility with a wide array of web frameworks and libraries makes it a versatile language for crafting feature-rich websites and web applications.

Enterprise-Level Solutions

Java is renowned for its capability to handle large-scale enterprise applications. Its scalability and reliability are second to none, making it an ideal choice for businesses seeking to develop robust, secure, and efficient software solutions.

Android App Development

If you're a fan of Android apps, you can thank Java for a significant part of your app experience. Java is the primary language used for Android app development, ensuring a vast array of high-quality apps available for Android users.

Key Features and Advantages


Platform Independence

One of Java's standout features is its "Write Once, Run Anywhere" capability. This means that once you've written Java code, it can run on any platform that supports Java, making it a valuable tool for developers aiming for cross-platform compatibility.

Strong Security

Security is paramount in today's digital landscape, and Java takes this aspect very seriously. Its robust security features, such as bytecode verification and the ability to run in a sandbox, make it a trusted choice for applications requiring top-notch security.

Rich Ecosystem

Java boasts a rich ecosystem of libraries, frameworks, and tools that simplify and expedite the development process. From Spring Framework to Hibernate, Java developers have access to a vast array of resources to enhance productivity.

The Java Community


The Java community is a vibrant, dynamic, and globally distributed network of developers and enthusiasts. With a vast pool of knowledge and resources, it's no wonder that Java continues to thrive and adapt to the ever-changing demands of the tech world.

Staying Relevant: Java's Future


As technology advances at an unprecedented pace, Java continues to evolve to meet new challenges and opportunities. Recent Java versions have introduced features like Records, Pattern Matching, and Project Loom, further enhancing its capabilities and performance.

Conclusion

In a technology-driven world, the power of Oracle Java cannot be overstated. From web development to enterprise-level solutions, Java remains at the forefront of innovation. Its platform independence, security features, and rich ecosystem make it a compelling choice for developers worldwide.

Wednesday, October 18, 2023

Simplifying data access with MySQL and Jakarta Data

MySQL and Jakarta Data, Oracle Java Career, Oracle Java Skills, Oracle Java Jobs, Oracle Java Prep, Oracle Java Preparation, Oracle Java Tutorial and Materials

See how the Jakarta Data specification simplifies persistence.


Many applications, especially in the enterprise domain, persist or access data in some form. Relational databases are still by far the most used persistence mechanism even though they are being challenged by technologies such as NoSQL databases. This article explores some concepts for data access and looks at how the new Jakarta Data specification makes data access simpler than ever for application developers.

Data persistence


I begin this discussion by reviewing persistence concepts. If you are familiar with these concepts, feel free to skip this part and dive right into the next section, which contains sample code.

CRUD. The most common operations used in applications that persist data are create, read, update, and delete (CRUD) operations. CRUD operations are commonly associated with relational databases but can be applied to any persistence mechanisms. Writing code for these operations is usually repetitive work consisting mostly of boilerplate code.

ORM. Object-relational mapping (ORM), as the name suggests, takes care of mapping objects in an object-oriented language to data in a relational database. There are numerous ORM frameworks available to help developers with this task. Jakarta Persistence, previously referred to as JPA, is a specification that standardizes persistence management and object-relational mapping for Java applications.

The Repository pattern. There are several patterns and strategies—such as Data Access Object (DAO), Repository, Active Record, and others—that are commonly used for structuring the code associated with CRUD operations. In this article, I use the Repository pattern.

The intention of the Repository pattern (which you can read about in Martin Fowler’s Patterns of Enterprise Application Architecture) is to keep the specifics regarding persistence outside the application’s domain model. The repositories are classes that encapsulate the data access logic, thus decoupling the persistence mechanism from the domain model.

The Repository pattern has become popular and is widely used due to technologies such as Spring Data; it is no secret that Spring Data is the inspiration for Jakarta Data.

Jakarta Data. Jakarta Data is a new specification proposed to be included in Jakarta EE 11, which is planned to be released in the first half of 2024. By implementing the Repository pattern, Jakarta Data simplifies data access and reduces the amount of boilerplate code needed. Developers only need to define an interface representing the repository and an entity representing the database table. The implementation of Jakarta Data will supply the actual implementation of the repository.

A simple example with MySQL


This very simple example shows how Jakarta Data simplifies persistence for developers by eliminating the need for boilerplate code. The technologies used in this example are


You will also need to have Apache Maven and a JDK installed on your computer. This code has been verified on Java 20, but other versions may work as well.

The example in this code uses Open Liberty as the runtime. However, when there is another implementation available, you should be able to replace Open Liberty with the other implementation without changing any code.

Step 1. Verify that Apache Maven and a JDK are installed. You should see something such as the following:

$ mvn --version
Apache Maven 3.8.2 (ea98e05a04480131370aa0c110b8c54cf726c06f)
Maven home: /home/ivar/.sdkman/candidates/maven/current
Java version: 20.0.1, vendor: Eclipse Adoptium, runtime: /home/ivar/.sdkman/candidates/java/20.0.1-tem
Default locale: en_US, platform encoding: UTF-8

Step 2. Install and set up MySQL after downloading it directly from https://www.mysql.com/ or by using your favorite package manager. Here is an example of how to do it if you are using Ubuntu.

$ sudo apt-get install mysql-server

Step 3. Log in to MySQL Shell.

sudo mysql -u root

Step 4. Create a database and user.

mysql> create database dukes_data;
mysql> use dukes_data;
mysql> create user 'duke'@'localhost' identified by 'duke';
mysql> grant all privileges on dukes_data to 'duke'@'localhost';

Step 5. Get the code from my GitHub repository, and then compile and run it with Maven.

$ mvn liberty:run

The application is now ready to try out.

Step 6. Three endpoints are available.

  • List all greetings (GET)
  • Search for a greeting by greeter name (GET)
  • Add a greeting (POST)

Here’s how they work.

To list all greetings, use the following:

http://localhost:9080/dukes-data/api/greetings/

The following is the expected response because there’s no data yet:

[]

To search for Duke’s greeting, use the following:

http://localhost:9080/dukes-data/api/greetings/duke

Similarly, because there’s no data yet, here’s the response.

duke not found

To add Duke’s greeting, use this.

$ echo -n '{"message":"Hello from Duke", "name":"Duke"}' | http post :9080/dukes-data/api/greetings

To list all greetings again, use this.

http://localhost:9080/dukes-data/api/greetings/

Here’s the expected response.

[
  {
    id: 1,
    message: "Hello from Duke",
    name: "Duke"
  }
]

Finally, to search for Duke’s greeting again, use the following:

http://localhost:9080/dukes-data/api/greetings/duke

The expected response is

Hello from Duke

The example code


The application consists of four classes: GreetingApplication, GreetingResource, Greeting, and GreetingRepository.

GreetingApplication configures the Jakarta REST application. In this case, the only thing needed is the application path.

package dukes.data;

import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;

@ApplicationPath("/api")
public class GreetingApplication extends Application {
}

GreetingResource exposes the three API methods for retrieving all greetings, retrieving one greeting, and adding a greeting.

package dukes.data;

import jakarta.inject.Inject;
import jakarta.validation.Valid;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;

import java.util.List;

@Path("/greetings")
public class GreetingResource {

    @Inject
    private GreetingRepository greetingRepository;

    @GET
    @Path("/{name}")
    @Produces(MediaType.TEXT_PLAIN)
    public String findOne(@PathParam("name") String name) {

       return greetingRepository.findByNameIgnoreCase(name)
               .map(Greeting::getMessage)
               .orElse(name + " not found");
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<Greeting> findAll() {

        return greetingRepository.findAll()
                .toList();
    }

    @POST()
    @Consumes(MediaType.APPLICATION_JSON)
    public Response addGreeting(Greeting greeting) {

        Greeting saved = greetingRepository.save(greeting);
        return Response.ok("Created greeting: " + greeting.getId()).build();
    }
}

The Greeting class defines the entity that is being persisted in the database. It is a Jakarta Persistence entity with three fields. The @Entity annotation identifies it as a Jakarta Persistence entity, and the @Id and @GeneratedValue annotations define the primary key as well as how it should be generated. Other than that, it is just a plain old Java object.

package dukes.data;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Greeting {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    private String message;

    // constructor/getters/setters
}

The GreetingRepository is where things get interesting. It is a simple interface that extends CrudRepository and is annotated with @Repository. This information is enough for the Jakarta Data implementation to generate methods for all the CRUD operations as well as a couple of other convenience methods, such as count, existsById, and various finders.

package dukes.data;

import jakarta.data.repository.CrudRepository;
import jakarta.data.repository.Repository;

import java.util.Optional;

@Repository
public interface GreetingRepository extends CrudRepository<Greeting, Long> {

    Optional<Greeting> findByNameIgnoreCase(String name);
}

The only method defined by the developer is findByNameIgnoreCase. As the name implies, this method searches the database for rows with the provided name. Jakarta Data will generate a method that does exactly that.

Source: oracle.com

Saturday, October 14, 2023

Introducing the Visual Recognition spec for Java machine learning

Oracle Java, Oracle Java Career, Oracle Java Skills, Oracle Java Jobs, Oracle Java Prep, Oracle Java Preparation

The VisRec API, JSR 381, addresses common pain points for machine learning in Java.


There are not many machine learning (ML) coding options for Java developers, and the ML libraries currently available have several issues. Many are very complex and designed for data scientists, or they are Java wrappers around C/C++ libraries and don’t feel like Java tools.

Of course, one native Java library is the increasingly popular Tribuo. But that’s not all: For image recognition tasks, there’s JSR 381, Visual Recognition (VisRec) Specification. This JSR was released in early 2022 and was designed to address the following common pain points for ML in Java:

  • Many different incompatible data formats
  • Many different ML algorithms
  • Many confusing configuration parameters
  • Lack of a clear task-oriented interface that hides implementation details, such as Collections.sort()
  • Lack of simple and portable integration into existing Java applications and devices

The authors of the VisRec specification explained that “there are wide business implications for machine learning capabilities in all applications across many types of devices. VisRec is an important subset of ML. Right now, the primary language for ML is Python. We feel Java needs to play a major role in ML, starting with VisRec.”

The specification authors added that typically, the API will be used in conjunction with an ML engine, package, or set of libraries that “would execute on a server or set of servers (as most ML applications) and callable from either the server side or remotely from a distributed client (JavaFX, web, command-line).”

Common applications of visual ML include pattern recognition and classifications. Imagine training and then processing a series of images and videos.

  • How many dogs are in those still images? How many cats? How many lemurs? For videos, how many unique dogs were captured?
  • Is there a vehicle in a video, and if so, what type? Is it speeding? Did it go through a stop sign without stopping? Was it speeding through a neighborhood while people were attempting to legally cross the street? Could the registration plate be read?
  • Did a security camera show that a shopper at a self-checkout skipped scanning an item?
  • Was the product label correctly affixed to a product in an automated assembly facility?

Two of the JSR 381 coauthors, Frank Greco and Zoran Sevarac, had an online chat with Mala Gupta about the VisRec API and its goals. Greco is a senior consultant at Google and chair of the New York Java user group, JavaSIG. Sevarac is an associate professor at the University of Belgrade and a Java and AI deep-learning expert. Mala Gupta is a developer advocate at JetBrains and is a frequent Java Magazine author. All three are Java Champions.

Here are a few highlights from their conversation.

Gupta: What is the most common myth you hear from Java developers about ML in Java applications?

Greco: It’s that you must be a data scientist to do ML. Of course, there will be some experts, but the bulk of the people using ML are not going to be data scientists. The core of ML is recognizing patterns, building models based on that data, and making predictions. Python is the default when it comes to ML, but we wanted to create something for Java, too.

Gupta: What exactly is JSR 381?

Greco: From a high level, it’s a Java-friendly standard API. It’s not only for visual recognition; it’s also a generic ML API. It includes the usual high-level abstractions. It uses Java paradigms. It’s more readable. The bottom line: It was designed for Java developers.

Gupta: What was your primary goal when developing JSR 381?

Sevarac: The main goal was to make visual recognition and ML easy to use by nonexperts. Java developers should be able to use this API intuitively and use their Java skills to the maximum extent, so they don’t have to learn new things. Or, if they do need to learn new things, they can learn them along the way through coding. We were also aware that it was not possible for us to implement all potential use cases in all possible learning algorithms. Therefore, the important point is to stay open, so any existing ML libraries out there can implement this API without much difficulty. We have created a reusable design, which can be applied to other domains, too.

Gupta: Several Java ML libraries already exist. Why develop JSR 381?

Sevarac: There are many libraries with different sets of APIs, but none of them works well with the others. Each library tries to reinvent the wheel. Our idea was to create a standard API collection that would address the most typical use cases and that would be extendable, so any existing ML library could easily implement it.

Also, existing libraries support different specific sets of algorithms and there are no common abstractions, or they are not compatible with each other. When it comes to visual recognition, there are so many Java imaging libraries that use different images and classes, and some of them use native dependencies, which creates portability issues. Most of these libraries do not look like Java and are very complex for the average Java developer, not only because the API is not Java flavored but also because most application developers don’t have a background in data science or know how ML algorithms work and how to configure them. These are all issues we are trying to address with JSR 381.

Gupta: What are some of the common barriers for ML in Java that you tried to address with JSR 381?

Sevarac: We tried to create abstractions where you can specify, with generic parameters, what type of data you’re going to use. There are many different ML algorithms, and we tried to create abstractions for the most common ones. Existing and new libraries should consider implementing some of these abstractions.

Confusing configuration parameters are one of the biggest challenges for every ML algorithm. We tried to keep those to a minimum and provide reasonable defaults—or at least some starting points people can use to create models. Learning these parameters will come with experience.

One of the most important things we addressed is providing a clear, task-oriented interface. It is very simple and straightforward.

Also, we felt it was important to hide implementation details. Developers don’t necessarily want to know details about how an image is being stored in memory and the most efficient way calculations are performed on that image. That might be important for the people who are implementing the algorithms, but end users generally don’t need those details.

Finally, JSR 381 provides simple and portable integration into existing Java applications and devices because the reference implementation is pure Java. It does not have native dependencies. That makes it very portable. You get all the benefits of the Java ecosystem.

Gupta: How would you sum up JSR 381 and its impact on the Java community?

Sevarac: We believe we created something that can evolve into a friendly Java API for developers. We could not solve all problems for everyone, but I think this is a good starting point. I believe that with feedback from the community, we can move this forward.

Source: oracle.com

Friday, October 13, 2023

Java Card 3.1: Enhanced deployment model and core features

Java Card 3.1 introduces an extended file format, the management of static resources, binary compatibility improvements, and the support of array views. Those features evolve the deployment and upgrade of applications, and they permit better design modularity and security as well.

Extended CAP file format and deployment model


The base unit in the Java Card deployment model is the Java Card converted application (CAP) file. A CAP file contains all the classes and interfaces defined in a Java Card application or library. CAP files are installed on a Java Card product either at manufacturing time or once the product is deployed in the field by using a trusted service manager (TSM).

Until the 3.1 release, a CAP file contained only a single Java package (application or library) and was limited to 64 KB. In some cases, this caused application design constraints and remote management complexity due to the splitting of a secure service into several CAP files. To circumvent those issues, the 3.1 release introduces an extended CAP file of up to 8 MB that provides these benefits:

  • The extended CAP file can contain multiple Java packages of applications and libraries. This eliminates design constraints and reduces the number of CAP files deployed by a TSM.
  • A Java package can be private to a given application in contrast to public and shared packages that can be accessed by different applications available on the platform. This allows for a better design and for finer-grained access control.

Taking the example of an IoT application that uses two libraries, one for a dedicated storage hierarchy and one for a dedicated protocol to access a given IoT cloud service, there are three Java packages. If those packages’ implementations require utility packages—such as for asn.1 parsing and JSON parsing, which are generic and can be shared among different applications on the same platform—that can mean a total of five Java packages.

Without using the extended CAP file format, this would lead to five CAP files to deploy. Thanks to the new format, this can be reduced to one or any other combination that makes sense. Figure 1 shows a combination of two CAP files. Deployment complexity is greatly reduced. Access control is also better addressed because the libraries (protocol and storage) dedicated to the IoT application are now accessible only by the IoT application itself.    

Java Card, Oracle Java Career, Oracle Java Skills, Oracle Java Jobs, Oracle Java Prep, Oracle Java Preparation, Oracle Java Tutorial and Materials, Oracle Java Model, Oracle Java Guides Exam

Figure 1. Combining CAP files

Static resources in the CAP file


Java Card 3.1 supports static, read-only resources in CAP files. These resources are accessible only from the code included in the same CAP file via an associated identifier. CAP files offer implementation alternatives to store data out of the object heap. Examples of static resources could be a configuration used the first time an application starts, default parameters or a security policy, precomputed values or data patterns, and more.

Binary compatibility improvement


Evolving an API while ensuring backward compatibility is a challenge on any platform. The Java Card 3.1 virtual machine overcomes a limitation preventing the extension of the method set of a nonfinal class as well as a virtual machine mapping table (VMMT). As shown in Figure 2, this enhancement simplifies the upgrade of an API using either the Java Card API itself or a user library.
This enhancement is itself fully backward compatible and does not require a recompilation of existing packages. Only libraries containing classes upgraded with new methods will use this feature. Similarly, if an application code update uses the new methods in an upgraded API, the application will automatically use these code extensions.

Java Card, Oracle Java Career, Oracle Java Skills, Oracle Java Jobs, Oracle Java Prep, Oracle Java Preparation, Oracle Java Tutorial and Materials, Oracle Java Model, Oracle Java Guides Exam

Figure 2. Example of binary compatibility improvement

Array views


In certain scenarios, an application might need to access, process, or share a subset of an array instead of the whole array. Creating a defensive copy of the data in a separate array requires additional memory and data synchronization between the original array and the copy of its subset. Java Card 3.1 provides an alternative mechanism called array view, as shown in Figure 3. There are two big benefits of array view.

Java Card, Oracle Java Career, Oracle Java Skills, Oracle Java Jobs, Oracle Java Prep, Oracle Java Preparation, Oracle Java Tutorial and Materials, Oracle Java Model, Oracle Java Guides Exam

Figure 3. Example of an array view created on a subset of a parent array’s elements

The first benefit is simplified design and code modularity. An application can create an array view on a subset of the elements of a parent array and then use this array view when calling code in another module or running service. This greatly simplifies API design. Array views can be used directly as input or output parameters without the need to copy data, manage an offset, or implement any data synchronization protocol.

Array views also provide improved access control and security for sharing data between applications. An array view is a temporary array object to which are assigned read and write access control attributes. These control attributes enforce security by design and are useful, for instance, when an API returns a view from internal memory that must not be modified, such as when the field of a certificate object is accessed. In addition, as in shown in Figure 4, when an array view is created to share data between two applications (two firewall contexts), the application sharing the array view can specifically designate which application context it is sharing.

Java Card, Oracle Java Career, Oracle Java Skills, Oracle Java Jobs, Oracle Java Prep, Oracle Java Preparation, Oracle Java Tutorial and Materials, Oracle Java Model, Oracle Java Guides Exam

Figure 4. Example of array view sharing data

Source: oracle.com

Wednesday, October 11, 2023

Javadoc documents are great—and better than ever with @snippets

JEP 413, delivered in Java 18, makes Java documentation easier to create than ever.


Say goodbye to incorrect or outdated code snippets in Javadoc documentation! The new @snippet tag, delivered in JEP 413 with Java 18, is an effective solution for including code snippets in the documentation. This improvement will facilitate better code quality, improve software development, and encourage more developers to use the Java API.

Java developers write functional code, and they are also responsible for documenting it correctly, as Andrew Binstock explained in “Reduce technical debt by valuing comments as much as code.” One way of documenting your Java application is by using the Javadoc tool, which has long used tagged comments you insert within your source code to describe parameters, return values, exceptions thrown, and so on. In some cases, it is necessary to include a code snippet to demonstrate the intended use of the code.

Before Java 18, the @code tag and the <pre> and </pre> tags were used to indicate multiline snippets, and adding code examples to API documentation using Javadoc was a tedious process. Special characters such as <, >, and & had to be escaped, and handling indentation was difficult. The biggest issue, however, was that a code snippet had to be specified within the Javadoc comment itself. This made it challenging to create code snippets, and there needed to be a way to verify if the code was accurate. The result? Sometimes you had code snippets that wouldn’t compile, either due to an author oversight or API changes that weren’t reflected in the Javadoc comments. That really limited the value of code snippets as documentation.

However, there’s always room for improvement, and that’s precisely where JEP 413 comes in. The code snippets in the Java API documentation proposal specified in JEP 413 revolutionizes Java API documentation by making it more user friendly and accessible to developers. It’s now easier to include inline code snippets as well as external source files within the documentation. This will enable you to edit, refactor, compile, and test the example code using your regular Java toolchain.

Adding code snippets to Javadoc documentation will help future maintainers of your code understand better how to use your classes and methods. They’ll have an easier time writing quality code, and software development will improve overall.

Code snippets can come in the following three forms:

  • Inline: A snippet that contains the content of the snippet within the tag itself
  • External: A snippet that refers to a separate class or file that contains the content of the snippet
  • Hybrid: A snippet that contains both internal and external content

The @snippet tag


JEP 413 introduced a new tag, {@snippet ...}, for code fragments in Javadoc-generated documentation. A snippet may have attributes in the form of name=value pairs, and values can be quoted with a single-quote character (') or a double-quote (") character. These name=value pairs can be added to the tag to provide more details and may include an id to identify the snippet in both the API and in the generated HTML, which may be used to create a link to the snippet.

Snippet code fragments are typically Java source code, but they can be other types of content. They may have a lang attribute to identify the kind of content (such as properties files, source code, or plain text) in the snippet (the default is Java) or to infer the type of line comment or end-of-line comment that may be supported in that language.

You can add markup tags (such as @highlight, @link, and @replace) within the code to indicate how to present the text, usually in the form of @name arguments.

Inline snippets


The most straightforward usage is to use an inline @snippet tag and include some code (or text) between the first new line after the colon (:) and the closing curly brace (}) of the tag itself, as in the following example:

/**
 * A demo of the @snippet tag to include non-escaping special characters.

 * {@snippet id='specialChars' :
 * int age = 42;
 * <html>Here is HTML tags works</html>
 * & also works;
 * @ also works;
 * }
 */

public void snippetsSpecialCharacters() {
    System.out.println("Code @snippets special characters demo.");
}

Then, the Javadoc function of your IDE-generated documentation will be similar to what’s shown in Figure 1.

Oracle Java, Java Career, Java Skills, Java Jobs, Java Prep, Java Preparation, Java Tutorial and Materials, Java Guides

Figure 1. The new Javadoc snippet functionality shows how special characters work without requiring an escape sequence.

You should immediately notice a few improvements over the <pre>{@code ...}</pre> way of creating Javadoc documentation.

  • It’s easier to type with less clutter in the source file.
  • There’s no need to escape special characters such as <, @, >, or & with HTML entities.
  • The documentation has a grey background, which makes snippets more visible.
  • In the upper right corner, there’s a Copy button that copies snippets to the clipboard in plain text.

By the way, when you’re using inline snippets, the content can’t have the character pair */ because that would terminate the Javadoc comment. Also, parsing @snippet source code means Unicode escape sequences (\uNNNN) will be interpreted and can’t be differentiated from characters. In addition, all curly bracket characters ({}) must be balanced (that is, have the same number of left and right curly brackets nested) so the closing curly bracket of the @snippet tag can be determined.

Regions. Regions define a range of lines in a snippet and the scope for actions such as text highlighting or modification. Regions are marked by @start region=name or by @highlight/@replace/@link tags. A region ends with @end or @end region=name, which ends the region that has the matching name. You can create overlapping regions, but I wouldn’t recommend it; it could be confusing.

Highlighting. Use the @highlight tag to highlight text within a line or a region and to specify the content to highlight as a literal string (using a substring argument) or as a regular expression (using a regex argument). Additionally, use region to define the scope for where to find the text to be highlighted, and use type to determine the type of highlighting by using bold, italic, or highlighted. If no type is specified, the entire line is formatted in bold. In the following example, a basic regular expression is used to highlight the content of a string literal:

/**
 *  Demo for code @snippets highlighting.
 * {@snippet id="highlighting" lang="java" :
 * (1) System.out.println("Code highlighting with 'regex'"); // @highlight regex='".*"'
 * (2) public record Point (int x, int y){}; // @highlight type=highlighted
 * (3) Point point = new Point(10, 30); // @highlight
 *
 * // @highlight region="output" substring="System.out" type="italic" :
 * (4 -->)
 * (5) System.out.println(point); // @highlight substring="point" type="italic"
 * (6) System.out.println(point.x()); // @highlight substring="point" :
 * (7) System.out.println(point.y()); // @highlight substring="out" type="highlighted"
 * (8) System.out.println(point.y()); // @highlight substring="y()" type="highlighted"
 * (<-- 4)
 * // @end region="output"
 * }
 */

public void demoHighlight() {
    System.out.println("Code @snippets highlighting demo.");
}

Running your IDE’s Javadoc function on the previous code snippet would generate the output shown in Figure 2.

Oracle Java, Java Career, Java Skills, Java Jobs, Java Prep, Java Preparation, Java Tutorial and Materials, Java Guides

Figure 2. Code snippets that demonstrate highlighting

How does the output correspond to the resulting Javadoc documentation? In line 1 of the code example, //@highlight regex='".*"' marks all the content between double quotes in the println() method to be formatted in bold, the default highlighting type. In line 2 of the code example, I wanted to highlight the whole line with an orange background, so I used //@highlight type=highlighted. In line 3 of the code example, I wanted to highlight the entire code for the creation of the Point object point and its assignment to coordinates, so I used only //@highlight; the whole line is formatted in bold.

In line 5 of the code example, I used slightly more-complex highlighting by marking only one word (a substring)—point—in italics. In this case, I specified the substring and the highlighting using //@highlight substring="point" type="italic".

The first four examples highlighted something in the same line of code. However, you can also control the highlighting of the next line in the code snippet. For instance, in line 6 of the code example, I applied highlighting to the next line in the code snippet by adding a colon (:) at the end of line 6. The space before the colon is optional, but it enhances readability. Thus, point (in the point.y() part) will become bold, as shown in line 7 of Figure 2.

A potential problem can occur due to personal style: Some developers might prefer highlighting to affect the current line, but others might prefer highlighting to affect the next line. Both ways are permitted by the JEP 413 specification. My recommendation: Stick to one convention within your codebase.

To add background color for a specific part of the code, use type="highlighted"—as shown in line 7 of the code example. There, the //@highlight substring="out" type="highlighted" formats out with an orange background in line 7 of Figure 2.

You might have observed that out is also written in italics in line 7 of Figure 2. This is because in the code example, the code between (4 -->) and (<-- 4) uses the //@highlight substring=System.out type=italic region=output definition, which applies italic highlighting to all matching substrings in this region. Since all the substrings are italicized, the preceding line adds an orange background to out, and this demonstrates how highlights can be combined.

Finally, all named regions must be closed with the //@end markup tag: //@end region=output.

Linking. You can provide additional information in Javadoc documentation by linking a text fragment to other parts of the documentation, whether to internal parts (such as to other documentation comments on the same page) or to external content (such as to a documentation comment of another class or even to a JDK class). To accomplish this, use the @link markup tag within the contents of @snippet followed by arguments to link the text to declarations in the API.

The arguments should specify the scope of the text to be considered, the text within that scope to be linked, and the link’s target. If region or region=name is provided, the scope will be that region up to the corresponding @end tag. If neither is specified, the scope will be limited to the current line.

To link each instance of a literal string within the scope, use the substring=string attribute. To link each instance of text matched by a regular expression within the scope, use regex=string. If neither of these attributes is specified, the entire scope will be linked. You can set the target with the target parameter and specify the type of link: link (the default) or linkplain. Consider the following example:

/**
 *  Demo for code @snippets Linking.
 * {@snippet id="linking" lang="java" :
 * // @link substring="System.out" target="System#out":
 * System.out.println("Link to System.out");
 * final App app = new App();
 * // @link substring="demoLinking()" target="#demoLinking" type="link" :
 * app.demoLinking();
 * }
 */
    
public void demoLinking() {
    System.out.println("Code @snippets Linking demo.");
}

Figure 3 shows the corresponding Javadoc documentation.

Oracle Java, Java Career, Java Skills, Java Jobs, Java Prep, Java Preparation, Java Tutorial and Materials, Java Guides

Figure 3. How to link code snippets

The opening line in the Javadoc documentation shown in Figure 3 links to the well-known out instance of the java.lang.System class. The icon displayed next to System.out is worth noting; it indicates this is an external link. In contrast, no icon appears next to demoLinking(), because it’s an internal link. Like many hyperlinks on the internet, the color of these links is adjusted when you hover over them, serving as another sign that they are clickable.

Modifying text. Sometimes you might want to perform a search-and-replace operation using a placeholder value in the text of an example and then use a marker comment to indicate that the placeholder should be substituted with alternate text in the final output.

Use @replace to replace some text with replacement text within a line or region and follow that with arguments that specify the scope of the text to be considered. Use substring with the literal expression or regex with a regular expression for the text to be replaced, and set the region to define the scope for where to find the text to be replaced. Finally, use replacement for the replacement text. Consider the following example:

/**
 *  Demo for code @snippets Text Replacement.
 * {@snippet id="linking" lang="java" :
 *   public static void main(String... args) {
 *      var text = "Mohamed Taman"; // @replace regex='\".*\"' replacement=" ... "
 *      System.out.println(text);   // @replace substring='System.' replacement=""
 *   }
 * }
 */

public void demoReplacement() {
    System.out.println("Code @snippets Text Replacement Demo.");
}

In the example above, a text variable of type substring with the value Mohamed Taman is used as the placeholder value, and the @replace tag is used to specify that it should be replaced with an ellipsis. (I doubt you’ll find a real-life application for that specific example.)

Here are two final tricks. To delete text, use @replace with an empty string as I did for System. To insert text, replace nonoperative text with @replace. No-op text can be // or an empty statement.

You can see the output for the code above in Figure 4.

Oracle Java, Java Career, Java Skills, Java Jobs, Java Prep, Java Preparation, Java Tutorial and Materials, Java Guides

Figure 4. Code snippets after text replacement

External snippets

Although inline code snippets are suitable for many scenarios, there may be instances where more-advanced functionality is required. For example, external code snippets are necessary to integrate external code snippets with block comments that refer to a separate class or file containing the snippets’ content.

You can place external files in a subdirectory, called snippet-files, of the package that contains the snippet tag. Alternatively, when you run Javadoc, you can specify a separate directory using the --snippet-path option.

The example below demonstrates how to lay out the external snippet. It consists of a directory named src/org, which contains the source code for a class named App.Main, an image named icon.png in the doc-files subdirectory, and several files for external snippets—ExternalSnippet.java, ExternalSnippetWithRegions.java, external-prop-Snippet.properties, and external-html-snippet.html—in the snippet-files directory. The StandardDoclet class can locate the external snippets in this example without additional options.

$ tree
       .
└── src
           └── org
  ├── App.java
  ├── doc-files
  │ └── icon.png
  └── snippet-files
                    ├── ExternalSnippet.java
                    ├── ExternalSnippetWithRegions.java
                    ├── external-prop-Snippet.properties
                    └── external-html-snippet.html

The external file for a snippet can be specified by using either the class attribute for Java source files or the file attribute for other file types. Here’s an example of a snippet referencing an external class called ExternalSnippet.java that has the following contents.

public class ExternalSnippet {
    /**
     * The ubiquitous "Hello, World!" program.
     */
    public static void main(String... args) {
        System.out.println("Hello, World!");
    }
}

You can reference ExternalSnippet.java in the code snippet as follows:

/**
 *  Demo for code @snippets with external code snippets.
 * {@snippet class=ExternalSnippet }
 */

public void demoExternalSnippet() {
    System.out.println("Code @snippets referencing external java file Demo.");
}

As you can see, the colon, newline, and subsequent content can be omitted in an external snippet. However, it is not surprising that the generated output, shown in Figure 5, looks similar to the external source file.

Oracle Java, Java Career, Java Skills, Java Jobs, Java Prep, Java Preparation, Java Tutorial and Materials, Java Guides

Figure 5. Code snippets can reference an external Java file.

Referencing non-Java files. External snippets aren’t restricted to Java source files. Any structured text suitable for display in an HTML <pre> element can be used. You can reference non-Java files such as external-html-snippet.html and the properties file external-prop-Snippet.properties. Consider the following external-html-snippet.html example:

<!DOCTYPE html>
<html lang="en">
    <body>
        <ol>
            <li>Hello Snippets</li>
            <li>I am an external HTML file to include in the @snippet</li>
        </ol>
    </body>
</html>

You can reference it with the following:

/**
  *  Demo for code @snippets with external html file.
  * {@snippet file='external-html-snippet.html' }
  */

public void demoExternalSnippetHtml() {
    System.out.println("Code @snippets referencing external html file Demo.");
}

The output will appear as shown in Figure 6.

Oracle Java, Java Career, Java Skills, Java Jobs, Java Prep, Java Preparation, Java Tutorial and Materials, Java Guides

Figure 6. Code snippets can reference an external HTML file.

Using only parts of an external file. Now imagine that you have the following external properties external-prop-Snippet.properties file, and you want to reference a specific region (region=house) and highlight the street name inside that region. The file’s content would be as follows:

client.name=Mohamed Taman
# @start region=house
house.number=42
# @highlight substring="Durmitorska St." :
house.street=Durmitorska St.
house.town=Belgrade, Serbia
# @end region=house
client.email=mohamed.taman@gmail.com

Here’s how to reference the file inside the @snippet tag.

/**
 *  Demo for code @snippets with external properties file with highlighting.
 * {@snippet file='external-prop-Snippet.properties' region=house }
 */

public void demoExternalSnippetProperties() {
    System.out.println(""" 
          Code @snippets referencing external
          properties file with highlighting Demo.
          """);
}

The output will be as shown in Figure 7.

Oracle Java, Java Career, Java Skills, Java Jobs, Java Prep, Java Preparation, Java Tutorial and Materials, Java Guides
Figure 7. A code snippet that references one region of an external properties file

Formatting and linking within an external Java snippet. Regrettably, there is a drawback when you use highlighting with external snippets. You cannot define a region using @highlight region=reg1 (or @link region=reg1 or @replace region=reg1) and then refer to that region within the main source file. The only option is to define a region in an external snippet using @start region=reg1. Therefore, you can highlight, replace, or link to only a single line within the region.

Note: This limitation doesn’t exist for internal snippets, as shown in the previous external properties file example, Figure 7, or the following Java-based example:

public class ExternalSnippetWithRegions {
    /**
     * The ubiquitous "Hello, Snippets World!" program.
     */

    public static void main(String... args) {
        // @start region=main
        /*
          Print Hello world
         */
        System.out.println("Inside region Main"); // @highlight regex='".*"'

        // Join a series of strings // @start region=join
        var delimiter = " ";        // @replace regex='".*"' replacement='"..."'
        var result = String.join(delimiter, args); // @link substring="String.join" target="String#join"
        // @end region=join
        // @end region=main
    }
}

When the above is referenced as follows

/**
 *  Demo for code @snippets with external Java code file with region and highlight.
 * {@snippet class=ExternalSnippetWithRegions region=main}
 */

public void demoExternalSnippetRegions() {
    System.out.println("Code @snippets referencing external java file region Demo.");
}

it will be rendered as shown in Figure 8.

Oracle Java, Java Career, Java Skills, Java Jobs, Java Prep, Java Preparation, Java Tutorial and Materials, Java Guides
Figure 8. Code snippets can reference an external Java file with region and highlight.

Hybrid snippets

External snippets are convenient for testing purposes. Inline snippets offer context within a comment. Hybrid snippets combine the benefits of both, though with slightly less convenience. They include attributes for specifying an external file and possibly a region.

To ensure consistency, StandardDoclet verifies that processing the snippet as both inline and external snippets yields the same result. It’s recommended that you develop the snippet initially as either an inline or external snippet and then convert it to a hybrid snippet later.

The example below merges an inline and an external snippet using region=join (from the previous ExternalSnippetWithRegions.java example) to create a hybrid snippet. It’s worth noting that the inline content differs slightly from the region’s content in the external snippet. The external snippet utilizes a @replace tag to ensure it is compilable code, while the inline snippet displays ... directly for readability purposes.

The content from the external file ExternalSnippetWithRegions.java is as follows:

public class ExternalSnippetWithRegions {
  ...
  // Join a series of strings // @start region=join
  var delimiter = " ";        // @replace regex='".*"' replacement='"..."'
  var result = String.join(delimiter, args); // @link substring="String.join"      
  target="String#join"
 // @end region=join
 ...
}

And the inline snippet is as follows:

/**
 * Demo for code Hybrid Snippets.
 * {@snippet class=ExternalSnippetWithRegions region=join :
 * // Join a series of strings
 * var delimiter = "...";
 * var result = String.join(delimiter, args);
 * }
 */

public void demoHybridSnippets() {
    System.out.println("Code for Hybrid Snippets Demo.");
}

The output is shown in Figure 9.

Oracle Java, Java Career, Java Skills, Java Jobs, Java Prep, Java Preparation, Java Tutorial and Materials, Java Guides
Figure 9. Hybrid code snippets

Source: oracle.com