DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

Related

  • Exploring Embeddings API With Java and Spring AI
  • GenAI in Java With Merlinite, Quarkus, and Podman Desktop AI Lab
  • AI in Java: Building a ChatGPT Clone With Spring Boot and LangChain
  • Build an AI Chatroom With ChatGPT and ZK by Asking It How!

Trending

  • Build AI Agents With MCP Server in C# and Run in VS Code
  • Designing Microservices Architecture With a Custom Spring Boot Starter and Auto-Configuration Framework
  • Stop Building Monolithic AI Brains, Build a Specialist Team Instead
  • From Java 8 to Java 21: How the Evolution Changed My Developer Workflow
  1. DZone
  2. Data Engineering
  3. AI/ML
  4. Supercharge Your Java Apps With AI: A Practical Tutorial

Supercharge Your Java Apps With AI: A Practical Tutorial

A practical, code-rich tutorial showing Java developers AI integration via TensorFlow and OpenAI with examples like NLP, chatbots, and image processing.

By 
Alok Tibrewala user avatar
Alok Tibrewala
·
Jun. 04, 25 · Analysis
Likes (3)
Comment
Save
Tweet
Share
2.7K Views

Join the DZone community and get the full member experience.

Join For Free

Artificial intelligence (AI) offers great potential for software applications by providing options like natural language processing, image recognition, and predictive analysis, which can be integrated within software. 

This tutorial aims to empower developers to unlock advanced functionalities by providing a blend of theoretical insights and practical, code-centric examples, allowing for seamless integration of AI in their Java applications.

AI Foundations for Java Developers

AI offers a host of techniques that enable software to mimic human intelligence, such as reasoning, pattern recognition, and natural language understanding. At its very core, machine learning (ML) uses exposure to data to enhance the performance of its algorithms. Deep learning, on the other hand, is a specialized subset of ML that uses neural networks to identify intricate patterns. This makes Deep Learning an ideal choice for tasks like image classification and language generation.

Java developers have a choice of various frameworks and APIs, such as TensorFlow, Deeplearning4j, and OpenAI, to harness the power of AI. These libraries and frameworks will not only offer cutting-edge AI capabilities but also ensure to do so gracefully by ensuring scalability and efficiency.

Essential Tools and Frameworks

Some of the options to integrate AI in Java applications are,

  1. Deeplearning4j – A Java-native deep learning library that can be used for seamless integration into a Java application
  2. TensorFlow Java API – Google's AI framework for machine learning, deep learning, etc.
  3. OpenAI API – A cloud-based service that can be used for advanced language tasks, allowing developers to add smart language features using prompt engineering

This tutorial focuses on the TensorFlow Java API and OpenAI API due to their powerful features, extensive documentation, and developer-friendly interface, which makes them ideal for Java-based AI projects.

Environment Setup

To begin, add the following dependencies to the Maven project to enable TensorFlow and OpenAI API integrations:

XML
 
<dependencies>
    <dependency>
        <groupId>org.tensorflow</groupId>
        <artifactId>tensorflow</artifactId>
        <version>0.6.0</version>
    </dependency>
    <dependency>
        <groupId>com.theokanning.openai-gpt3-java</groupId>
        <artifactId>service</artifactId>
        <version>0.18.2</version>
    </dependency>
</dependencies>


Ensure Java version 8 or later is being used. For using TensorFlow, you may also need to install native libraries like libtensorflow_jni.

More details can be found at the following links:

  1. TensorFlow Java documentation
  2. For using OpenAI, an API key is needed, which can be obtained from OpenAI’s website

Practical AI Implementations in Java

Let's dive into practical examples showing the integration of AI with Java.

1. Image Classification With TensorFlow

This example shows how a pre-trained TensorFlow model can be loaded to classify images, demonstrating the power of deep learning in visual recognition.

Java
 
import org.tensorflow.*;
import java.nio.file.Files;
import java.nio.file.Paths;

public class ImageClassifier {
    public static void main(String[] args) throws Exception {
        byte[] graphDef = Files.readAllBytes(Paths.get("model.pb"));
        try (Graph graph = new Graph()) {
            graph.importGraphDef(graphDef);
            try (Session session = new Session(graph)) {
                Tensor<Float> input = preprocessImage("image.jpg");
                Tensor<?> result = session.runner()
                    .feed("input_tensor", input)
                    .fetch("output_tensor")
                    .run().get(0);
                System.out.println(processResults(result));
            }
        }
    }

    private static Tensor<Float> preprocessImage(String imagePath) {
        // Implement preprocessing (resize, normalization)
    }

    private static String processResults(Tensor<?> tensor) {
        // Interpret tensor output to obtain readable labels
    }
}


2. Natural Language Processing With OpenAI

This example uses the OpenAI API to generate human-like responses. The temperature can be adjusted to change the type of response. For a more deterministic and focused response, use temperature < 0.7, for a more creative use > 0.7.

Java
 
import com.theokanning.openai.OpenAiService;
import com.theokanning.openai.completion.CompletionRequest;

public class NLPExample {
    public static void main(String[] args) {
        String apiKey = "API_KEY";
        OpenAiService service = new OpenAiService(apiKey);

        CompletionRequest request = CompletionRequest.builder()
            .model("text-davinci-003")
            .prompt("Describe the benefits of integrating AI in Java.")
            .maxTokens(150)
            .temperature(0.7)
            .build();

        service.createCompletion(request)
            .getChoices()
            .forEach(choice -> System.out.println(choice.getText()));
    }
}


3. Sentiment Analysis Using TensorFlow

This example uses a pre-trained sentiment model to analyze sentiments. The output of the score will be between 0 and 1, where 0 represents a fully negative sentiment, while 1 represents a fully positive sentiment, and values in between will represent a sentiment leaning to negative or positive based on the value.

Java
 
import org.tensorflow.*;
import java.nio.file.Files;
import java.nio.file.Paths;

public class SentimentAnalysis {
    public static void main(String[] args) throws Exception {
        byte[] graphDef = Files.readAllBytes(Paths.get("sentiment_model.pb"));
        try (Graph graph = new Graph()) {
            graph.importGraphDef(graphDef);
            try (Session session = new Session(graph)) {
                Tensor<String> input = Tensor.create("This is an amazing tutorial!");
                Tensor<?> result = session.runner()
                    .feed("input_tensor", input)
                    .fetch("output_tensor")
                    .run().get(0);
                System.out.println("Sentiment Score: " + processSentiment(result));
            }
        }
    }

    private static float processSentiment(Tensor<?> tensor) {
        // Convert tensor output into sentiment score
    }
}


4. Building a Chatbot With OpenAI

The following shows an example of using OpenAI to build a chatbot.

Java
 
import com.theokanning.openai.OpenAiService;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Chatbot {
    public static void main(String[] args) {
        String apiKey = System.getenv("API_KEY");
        OpenAiService service = new OpenAiService(apiKey);
        Scanner scanner = new Scanner(System.in);
        List<ChatMessage> conversation = new ArrayList<>();
        conversation.add(new ChatMessage("system", "A helpful assistant!"));

        while (true) {
            System.out.print("User: ");
            String userInput = scanner.nextLine();
            if (userInput.equalsIgnoreCase("exit")) break;

            conversation.add(new ChatMessage("user", userInput));
            ChatCompletionRequest request = ChatCompletionRequest.builder()
                .model("gpt-3.5-turbo")
                .messages(conversation)
                .maxTokens(100)
                .build();

            String response = service.createChatCompletion(request)
                .getChoices().get(0).getMessage().getContent();
            System.out.println("Bot: " + response);
            conversation.add(new ChatMessage("assistant", response));
        }
        scanner.close();
    }
}


Conclusion

As we see, integrating AI into Java applications can be as simple as integrating a library. Tools like TensorFlow and OpenAI API make it super easy for Java developers to harness the power of deep learning and natural language processing in their applications. This tutorial covered the essential steps to get started, like setting up the environment, getting an API key, with some real-life examples, image classifications, generating human-like responses, sentiment analysis, and building a simple chatbot.

Apart from being extremely simple to integrate, these frameworks are highly flexible and scalable. Whether you are enhancing an existing project or building a new application from the ground up, the code and concept provided here will build a good foundation on which to build your features. Feel free to experiment with different models and adjust parameters, such as temperature or classification methods, to suit your specific use case. 

Also, explore the vast and useful TensorFlow Java documentation and OpenAI documentation to get more information if your needs vary. As AI keeps on evolving, there are always exciting opportunities to supercharge your applications with new features and better intelligence.

So, what's next? Integrate a pre-trained model in your application and start feeling the power of AI. Drop your comments on how you see AI helping your application!

AI API Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Exploring Embeddings API With Java and Spring AI
  • GenAI in Java With Merlinite, Quarkus, and Podman Desktop AI Lab
  • AI in Java: Building a ChatGPT Clone With Spring Boot and LangChain
  • Build an AI Chatroom With ChatGPT and ZK by Asking It How!

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: