Skip to content
Volume J · The TensorCore.si Library

Java

Write once, run anywhere, at enterprise scale.

Java runs banks, Android apps and big data systems such as Hadoop, Spark and Kafka. Modern Java (21+) is concise, with records, pattern matching and virtual threads, and it has solid libraries for calling and serving AI models.

Prologue

Why learn Java?

Java is one of the most-used languages in business software. Learning it opens jobs everywhere and teaches solid object-oriented design.

  • Jobs: huge demand in finance, enterprise and Android.
  • Performance: the JVM's JIT compiler makes long-running services fast.
  • AI in production: LangChain4j, Spring AI and DJL bring LLMs and models into Java systems.
Prologue

Set up and run your first program

Install a JDK 21 or newer (for example Eclipse Temurin). Single-file programs run directly with java.

terminal
java -version
java Hello.java
Hello.java
public class Hello {
    public static void main(String[] args) {
        String name = "Ada";
        System.out.println("Hello, AI! Welcome to Java, " + name + ".");
    }
}
TipFor real projects use Maven or Gradle to manage dependencies.
Chapter 1

Variables and types

Java has primitive types (int, double, boolean) and objects (String, lists). var infers the type of local variables. final makes a variable constant.

Vars.java
public class Vars {
    public static void main(String[] args) {
        int layers = 32;
        double lr = 3e-4;
        var model = "llama3.1";          // inferred String
        final long params = 8_030_000_000L;
        boolean streaming = true;
        System.out.printf("%s %d layers, FP16 %.1f GB%n", model, layers, params * 2 / 1e9);
    }
}
Chapter 2

Control flow

if, classic and enhanced for loops, while, and modern switch expressions with arrows that return a value.

Control.java
for (int epoch = 0; epoch < 3; epoch++) System.out.println("epoch " + epoch);
for (String gpu : new String[]{"H100", "B200"}) System.out.println(gpu);
int bits = 8;
String name = switch (bits) {
    case 32 -> "FP32";
    case 16 -> "FP16";
    case 8 -> "FP8";
    default -> "other";
};
System.out.println(name);
Chapter 3

Classes and records

Classes bundle data and methods. A record is a short way to declare an immutable data class with constructor, getters, equals and toString generated for you.

Classes.java
record Gpu(String name, int vramGb) {
    boolean fits(double modelGb) { return modelGb <= vramGb; }
}
public class Classes {
    public static void main(String[] args) {
        var g = new Gpu("RTX 5090", 32);
        System.out.println(g + " fits 16 GB? " + g.fits(16));
    }
}
Chapter 4

Collections and streams

List, Map and Set are the core collections. Streams let you filter and transform data in a functional style.

Streams.java
import java.util.*;
var vram = Map.of("H100", 80, "H200", 141, "B200", 180);
List<String> big = vram.entrySet().stream()
    .filter(e -> e.getValue() > 100)
    .map(Map.Entry::getKey).sorted().toList();
System.out.println(big); // [B200, H200]
Chapter 5

Exceptions

Errors are exceptions. Catch them with try/catch; use try-with-resources so files and connections close automatically.

Errors.java
import java.nio.file.*;
try {
    String text = Files.readString(Path.of("prompt.txt"));
    System.out.println(text.length() + " characters");
} catch (java.io.IOException e) {
    System.err.println("Could not read file: " + e.getMessage());
}
Part II · AI with Java

AI with Java

Java is used to put AI into production systems: calling LLM APIs, running ONNX or PyTorch models with DJL, and building retrieval pipelines inside existing enterprise apps.

The essential libraries

LangChain4jLLM chains, tools, RAG and agents.
Spring AILLM and vector store integration for Spring Boot.
Deep Java Library (DJL)Run PyTorch, TensorFlow and ONNX models.
ONNX Runtime JavaFast model inference on CPU and GPU.

Gradient descent from scratch

Learn y = 3x + 0.5 with loops only.

Gradient.java
import java.util.Random;
public class Gradient {
    public static void main(String[] a) {
        var r = new Random(0); int n = 100;
        double[] xs = new double[n], ys = new double[n];
        for (int i = 0; i < n; i++) { xs[i] = -1 + 2.0 * i / (n - 1); ys[i] = 3 * xs[i] + 0.5 + 0.1 * r.nextGaussian(); }
        double w = 0, b = 0, lr = 0.1;
        for (int step = 0; step < 500; step++) {
            double gw = 0, gb = 0;
            for (int i = 0; i < n; i++) { double err = w * xs[i] + b - ys[i]; gw += 2 * err * xs[i] / n; gb += 2 * err / n; }
            w -= lr * gw; b -= lr * gb;
        }
        System.out.printf("w=%.2f b=%.2f%n", w, b);
    }
}
Part III · Build an AI agent

Build an AI agent in Java

LangChain4j turns Java methods into tools the model can call. Annotate a method with @Tool, describe the assistant as an interface, and the library runs the agent loop.

Your goal→Model plans→Tool call→Your code runs the tool→Result back to model→Final answer
Agent.java
// Maven: dev.langchain4j:langchain4j and dev.langchain4j:langchain4j-ollama
import dev.langchain4j.agent.tool.Tool;
import dev.langchain4j.model.ollama.OllamaChatModel;
import dev.langchain4j.service.AiServices;

public class Agent {
    static class Weather {
        @Tool("Get the current weather for a city")
        String getWeather(String city) { return "It is 24°C and sunny in " + city + "."; }
    }
    interface Assistant { String chat(String message); }

    public static void main(String[] args) {
        var model = OllamaChatModel.builder()
            .baseUrl("https://localhost:11434").modelName("llama3.1").build();
        Assistant bot = AiServices.builder(Assistant.class)
            .chatModel(model).tools(new Weather()).build();
        System.out.println(bot.chat("Should I take an umbrella in Lahore today?"));
    }
}

Method and builder names follow LangChain4j 1.x; check its documentation for your version.

Run it locallyInstall Ollama, run ollama pull llama3.1, and keep it running. The code talks to its OpenAI-compatible API at http://localhost:11434/v1, so the same program also works with vLLM, llama.cpp server or a cloud API by changing the URL, model name and adding an API key.
Part IV · Your path

Java learning roadmap

Tick items off as you go. Your progress is saved in this browser.

Beginner

Intermediate

Advanced

Part IV · Your path

Projects to build

Todo REST APIA Spring Boot service with a database.
Document Q&ASpring AI plus a vector store over PDFs.
Image classifierRun an ONNX model with DJL.
Reference

Java cheat sheet

TaskSyntax
PrintSystem.out.println(x)
Listvar l = new ArrayList<String>()
MapMap.of("a", 1)
Recordrecord P(int x, int y) {}
Lambdax -> x * 2
Switch exprcase 1 -> "one";
Reference

Common mistakes

  • Comparing strings with == checks identity; use .equals().
  • Integer overflow is silent: use long for large counts like parameters.
  • Catching Exception everywhere hides real bugs; catch specific types.
Reference

Where to go next

On TensorCore.si: Kotlin volume, How AI works.

Keyboard: [ previous language · ] next language · / search the library