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.
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.
Set up and run your first program
Install a JDK 21 or newer (for example Eclipse Temurin). Single-file programs run directly with java.
java -version
java Hello.javapublic class Hello {
public static void main(String[] args) {
String name = "Ada";
System.out.println("Hello, AI! Welcome to Java, " + name + ".");
}
}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.
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);
}
}Control flow
if, classic and enhanced for loops, while, and modern switch expressions with arrows that return a value.
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);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.
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));
}
}Collections and streams
List, Map and Set are the core collections. Streams let you filter and transform data in a functional style.
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]Exceptions
Errors are exceptions. Catch them with try/catch; use try-with-resources so files and connections close automatically.
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());
}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
Gradient descent from scratch
Learn y = 3x + 0.5 with loops only.
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);
}
}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.
// 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.
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.Java learning roadmap
Tick items off as you go. Your progress is saved in this browser.
Beginner
Intermediate
Advanced
Projects to build
Java cheat sheet
| Task | Syntax |
|---|---|
System.out.println(x) | |
| List | var l = new ArrayList<String>() |
| Map | Map.of("a", 1) |
| Record | record P(int x, int y) {} |
| Lambda | x -> x * 2 |
| Switch expr | case 1 -> "one"; |
Common mistakes
- Comparing strings with
==checks identity; use.equals(). - Integer overflow is silent: use
longfor large counts like parameters. - Catching
Exceptioneverywhere hides real bugs; catch specific types.
Where to go next
- dev.java — official tutorials
- LangChain4j docs — LLMs in Java
- Spring AI — AI for Spring apps
On TensorCore.si: Kotlin volume, How AI works.
Keyboard: [ previous language · ] next language · / search the library