AI vs ML vs Deep Learning vs Generative AI vs LLM: Explained for Java Developers
-
Last Updated: October 4, 2026
-
By: javahandson
-
Series

AI vs ML vs Deep Learning vs Generative AI vs LLM explained for Java developers, with tokens, embeddings, attention and Spring AI code examples.
Ask a room of Java developers whether ChatGPT is AI or ML, and you will hear five different answers. If you search for AI vs ML vs Deep Learning vs Generative AI vs LLM, you get ten diagrams and twenty definitions. But most of those pages target data scientists, not Java developers.
So in this guide, we will clear up these five terms once and for all. We will use simple language, Java analogies and a little bit of Spring AI code.
In the earlier articles of this series, we wrote real Spring AI code. We used ChatClient, connected multiple chat models and read token usage from a response. Now it is time to step back and understand what is happening inside the model.
By the end of this guide, you will know:
You do not need any maths background for this. If you can read a for loop, you can follow along. Let us get started.
Before we define each term, let us look at the whole family. Once you see the structure, the confusion goes away quickly.
The easiest way to picture these terms is a set of nested boxes. Each one sits inside the bigger one:
So every LLM is generative AI. Every generative AI model uses deep learning. Deep learning is a type of machine learning, and machine learning is a branch of AI. However, the reverse is not true. Not every AI system is an LLM.

These ideas did not appear together. Instead, each one grew out of the one before it:
| Period | Milestone |
|---|---|
| 1950s | The term “artificial intelligence” is coined at the Dartmouth workshop in 1956 |
| 1959 | Arthur Samuel uses the term “machine learning” |
| 1990s-2000s | ML goes mainstream in spam filters and recommendations |
| 2012 | Deep learning takes off after AlexNet wins the ImageNet contest |
| 2017 | Google researchers introduce the transformer architecture |
| 2022 | ChatGPT launches and generative AI reaches the public |
In short, the field moved from writing rules, to learning patterns, to creating new content.
The course material behind this series uses a lovely analogy. Imagine you are building a robot chef:
Keep this picture in mind. We will now open each doll one by one.
Artificial intelligence means making computers behave in smart, human-like ways. That includes thinking, learning, solving problems and making decisions.
For example, voice assistants like Siri and Google Assistant are AI. A self-driving car that uses sensors and rules is also AI. In fact, AI is the umbrella term for every smart computer system.
Here is the part that surprises many developers. AI does not always mean learning. Early AI systems were simply large sets of rules written by experts.
As Java developers, we have written this kind of “AI” many times. Look at this simple spam filter:
public boolean isSpam(String subject) {
String text = subject.toLowerCase();
return text.contains("lottery")
|| text.contains("free money")
|| text.contains("click here");
}This code makes a decision that looks smart. But a human wrote every rule. The program never learns anything new on its own.
Rules work well when the problem is small and stable. Sadly, real life is neither.
For instance, spammers change their words every week. “Lottery” becomes “l0ttery” overnight. Soon you have hundreds of rules, and each new rule breaks an old one. Rule engines in payment systems often grow like this until nobody dares to touch them.
So researchers asked a simple question. What if the computer could find the rules by itself, just by looking at examples? That question gave birth to machine learning.
| 💡 Interview Insight Interviewers often ask, “Is all AI machine learning?” The correct answer is no. AI is the broad goal of making machines act intelligently. ML is one way to reach that goal by learning from data. A rule-based expert system or a chess engine with hand-written logic is AI, but it is not ML. |
Machine learning is a branch of AI where computers learn patterns from data. We do not give them strict rules. Instead, we give them lots of examples.
For example, think of how a child learns to spot a cat. Nobody explains whiskers and ear shapes in detail. The child simply sees many cats, and the brain figures out the pattern. ML works the same way.
Let us go back to our spam filter. In ML, we collect thousands of emails that people have already marked as spam or not spam. Then a training algorithm studies them.
After that, the algorithm decides on its own which words matter and how much. In Java terms, it is like the model filling in these numbers for you:
// In ML, these weights are learned from data, not typed by a developer
Map<String, Double> learnedWeights = Map.of(
"lottery", 0.92,
"winner", 0.81,
"invoice", -0.35,
"meeting", -0.60);When a new email arrives, the model adds up the weights and makes a prediction. If spammers change their words, you simply retrain with fresh data. You do not rewrite your code.
You use machine learning every day, often without noticing:
Most of these systems work on structured data, like rows in a table. They usually predict a label or a number. For example, “fraud or not fraud” or “the price of this house”.
Also, classic ML models are fairly light. Many of them train and run happily on a normal CPU.
Deep learning is a more advanced form of machine learning. Its design takes inspiration from the way the human brain works.
Classic ML often needs a human to choose the useful features, such as word counts. Deep learning, however, finds those features by itself. That makes it great for messy data like images, audio and long text.
Neural networks are the building blocks of deep learning. Each network contains artificial “neurons” connected in layers.
First, each neuron receives some numbers, processes them and passes the result forward. Each connection has a strength, called a weight. During training, the network keeps adjusting these weights until its answers improve.
Why the word “deep”? Simply because these networks have many layers stacked one after another. Some modern models have more than a hundred layers.
Here is a simple way to picture it for images:
Similarly, text works in a layered way. Lower layers pick up grammar, like “I am” versus “He is”. Middle layers learn how words relate, such as which “bank” we mean. Higher layers capture meaning and intent, such as whether a review is happy or angry.
You already use deep learning in Google Photos, Google Translate and face unlock on your phone.
Deep learning needs a huge amount of maths, mostly multiplying large matrices. That is where the hardware matters.
Now, training a deep model means billions of these small operations. A GPU runs them in parallel, while a CPU would crawl through them. That is why AI companies buy GPUs by the thousands.
You will often see NLP in these discussions, so let us place it correctly. NLP stands for Natural Language Processing. It is the area of AI that helps machines read, write and understand human language.
NLP is not a separate doll in our set. Instead, it is a goal that cuts across the circles. Older NLP used rules and classic ML. Modern NLP mostly uses deep learning, and today LLMs do most of the heavy lifting.
Common NLP tasks include:
Chatbots, email auto-complete and translation apps are all NLP in action.
Generative AI is a group of deep learning models that create new content. That content can be text, images, music, video or code.
First, it learns from a huge number of examples. After that, it uses the patterns it learned to produce something original. It does not simply copy and paste from its training data.
This is the key difference between generative AI and the ML we saw earlier.
Experts call the first kind discriminative models and the second kind generative models. You do not need to remember the names. Just remember: one sorts things, the other makes new things.
Generative AI is a big family. Here are its main members:
So an LLM is only one kind of generative AI. A tool that generates images from text is generative AI, but it is not an LLM.
A large language model is a deep learning model trained on massive amounts of text. That text comes from books, websites, articles and code. As a result, it can understand and generate human-like language.
Why “large”? Because both the training data and the model itself are huge. Modern LLMs have billions of parameters. A parameter is simply one of those learned weights we saw earlier.
Remember the spam example, where humans labelled every email? LLMs do not need that. They learn with a trick called self-supervised learning.
Again, think about how a baby learns to talk. Nobody gives it a list of rules. It just hears tons of conversations and slowly notices patterns. After “Good”, people often say “morning”.
An LLM plays a similar guessing game with itself. It reads “I’m going to the store to buy some…” and guesses the next word. Then it checks the real next word in the text and adjusts its weights. After billions of rounds, it becomes very good at guessing.
Along the way, it builds a giant web of connections. “Rain” connects to “umbrella” and “clouds”. “Store” connects to “shopping” and “money”.
After this pre-training, chat models usually go through extra fine-tuning with human feedback. That step teaches them to follow instructions and answer politely.
Here is the most important idea in this whole article. At its core, an LLM does only one thing. It predicts the next piece of text based on the input.
It is like a super-smart autocomplete. Type “Once upon a” and it will most likely guess “time”.
Strictly speaking, it predicts the next token, not the next word. We will see what a token is in section 9.
If the LLM only guesses one token, how does ChatGPT write full paragraphs? The answer is a loop.
Here, a chat app, which the course calls an LLM wrapper, keeps feeding the model its own output. Here is a simplified view in Java. Please note that this is only a sketch, not real Spring AI code:
// Simplified sketch of what a chat wrapper does internally
List<Integer> tokens = tokenizer.encode(userPrompt + "<|end of prompt|>");
while (tokens.size() < maxTokens) {
int next = llm.predictNextToken(tokens); // guess one token
if (next == END_OF_TEXT) {
break; // model says "I'm done"
}
tokens.add(next); // eat its own output
}
return tokenizer.decode(tokens);The special end-of-prompt marker tells the model where your input ends. Similarly, the model can predict a special end-of-text token. When the wrapper sees it, the loop stops.
So, think of the LLM as the engine and the wrapper as the car. This loop also explains why answers appear word by word when you stream them.
| 💡 Interview Insight A popular interview question is, “Is ChatGPT an LLM?” The precise answer is no. ChatGPT is an application. It runs on top of LLMs, such as OpenAI’s GPT models. The app adds the chat loop, conversation history, safety filters and the user interface. The LLM itself only predicts the next token. |
Honestly, the numbers behind LLMs are hard to imagine. Here are a few that the model makers have published:
Training runs for weeks on thousands of GPUs. The industry is even worried about running out of fresh public text to train on.
The good news for us? As Java developers, we do not train these models. We call them through an API, just like any other REST service.
Now let us peek inside the model. Three ideas explain most of its magic: tokens, embeddings and attention.
Behind the scenes, your text goes through this journey:
Text -> Tokens -> Token IDs -> Vectors (embeddings) -> Model layers
AI models cannot read text directly. Instead, they only understand numbers. So the first step is to break text into small pieces called tokens.
A token can be:
Take the made-up word “playfulish”. The model may split it into “play”, “ful” and “ish”. So even though the word is not in any dictionary, the model can still handle it. That is how LLMs cope with typos, slang and new product names.
Why not use whole words? Because language is messy. Some words are rare, some are misspelled, and some languages have no spaces at all. On the other hand, single characters are too small. Reading “unbelievable” letter by letter takes 12 steps. Tokens are the sweet spot in between.
As a rule of thumb, one token is about three-fourths of an English word. So 100 tokens make roughly 75 words.
In addition, each model has a fixed vocabulary. It is a giant lookup table that maps every known token to a unique number, called a token ID.
| Model | Vocabulary size |
|---|---|
| BERT | about 30,000 tokens |
| Mixtral | 32,000 tokens |
| GPT-4 | about 100,000 tokens |
| Llama 3 | about 128,000 tokens |
What if a word is not in the vocabulary? The tokenizer splits it into smaller known pieces. For example, “multicloudready” may become “multi”, “cloud” and “ready”.
Tokens matter for one very practical reason. Hosted models charge you per token. Both your input and the model’s output count.
On top of that, every model has a token limit, called the context window. The model cannot see any text beyond that limit. For example, Llama 3.1 supports about 128,000 tokens. That limit is why chat memory and RAG need careful planning.
However, a token ID is just a number. It says nothing about meaning. So the model converts each token into a long list of numbers, called a vector or an embedding.
Here is a toy example with only five “topics”. Real models learn these dimensions on their own and never name them:
| Word | Royalty | Female | Leadership | Strength | Fictional |
|---|---|---|---|---|---|
| King | 9.5 | -8.0 | 7.5 | 6.0 | 2.0 |
| Queen | 9.5 | 8.0 | 7.0 | 5.5 | 2.0 |
“King” and “Queen” are almost the same, except in the female column. That is exactly how we think about them too.
At the start of training, these numbers are random. Then the model reads sentences like “The king and queen rule the land” millions of times. Slowly, words used in similar places get similar vectors.
Of course, real models use far bigger vectors. For example, GPT-3 uses 12,288 numbers per token. Llama 3 8B uses 4,096, and the largest Llama 3.1 model uses 16,384.
Because meaning becomes geometry, we can do maths with it. The famous example is:
embedding("king") - embedding("man") + embedding("woman")
≈ embedding("queen")In other words, subtracting “man” removes maleness but keeps royalty. Adding “woman” brings in femaleness. The result lands close to “queen”.
We can also measure how close two words are. The simplest way is the dot product. Multiply matching numbers and add them up:
King = [9, -5, 6] Queen = [8, -4, 6] (9 x 8) + (-5 x -4) + (6 x 6) = 72 + 20 + 36 = 128 -> strongly related
A big positive result means related. A result near zero means unrelated. In practice, most systems use cosine similarity, which is a dot product on normalised vectors. This is exactly how vector stores find similar documents in RAG.
| 💡 Interview Insight Interviewers like to test this confusion: “Are the embeddings inside an LLM the same as the embeddings you store in a vector database?” Not quite. Inside an LLM, every token gets an embedding as the first step of processing. For RAG, we use a separate embedding model, such as OpenAI’s text-embedding-3-small. It turns a whole sentence or chunk into one vector with 1,536 numbers, which we then store and search. |
“The cat sat on the mat” and “The mat sat on the cat” use the same words. Yet they mean very different things.
The reason is that transformers look at all tokens at once, so they miss the order by default. To fix this, the model adds position information to each token’s vector. In the original transformer, this was a simple addition:
FinalVector[i] = TokenEmbedding[i] + PositionalEmbedding[i]
Many newer models, like Llama, use a smarter variant called rotary position embeddings. The goal is still the same. Now each token knows both its meaning and its position.
However, static embeddings have one big weakness. The word “bank” gets the same vector in every sentence. But look at these two:
Attention fixes this. Think of it as a smart highlighter. For each word, the model asks, “Which other words should I focus on to understand this one?”
In the first sentence, “deposit” and “check” get most of the attention. So the model treats “bank” as a financial institution. In the second sentence, “river” and “sat by” win. So now “bank” means the edge of a river.
For instance, the model might give “deposit” 50% of its focus and “check” 30%. These numbers are only for illustration, but the idea is real. Attention lets meaning change with context, and that is the heart of the transformer.
Now that we know each term, let us compare them in one place:
| Point | AI | ML | Deep Learning | Generative AI | LLM |
|---|---|---|---|---|---|
| What it is | Any smart machine behaviour | Learning patterns from data | ML with many-layer neural networks | DL models that create content | GenAI models for text |
| Main output | Decisions or actions | Labels or numbers | Labels, numbers, features | New text, images, audio, video | New text and code |
| Typical data | Rules or data | Structured tables | Images, audio, text | Huge mixed datasets | Huge text datasets |
| Hardware | Any | CPU is often enough | GPU | Large GPU clusters | Large GPU clusters |
| Example | Chess engine, rule engine | Spam filter, fraud score | Face unlock, translation | DALL·E, Sora | GPT, Claude, Llama |
The simple rule to remember is this. Each column is a special case of the column to its left.
Theory is good, but we are Java developers. So let us see where each idea lives in Spring AI 2.0.1, the current stable release.
Spring AI gives a Spring-style interface for almost every concept we discussed:
| Concept | Where you meet it in Spring AI |
|---|---|
| LLM | ChatModel and ChatClient |
| Image generation (diffusion) | ImageModel |
| Speech and transcription | TextToSpeechModel and TranscriptionModel |
| Embeddings | EmbeddingModel and VectorStore |
| Tokens | Usage inside ChatResponse metadata |
| Context window | ChatMemory, such as MessageWindowChatMemory |
| Creativity and randomness | ChatOptions, such as temperature and topP |
Notice something nice here. As a result, you never write tokenizer or attention code yourself. Spring AI and the model provider handle all of that for you.
Let us prove that tokens are real. This endpoint asks a question and returns the token counts. It assumes the spring-ai-starter-model-openai starter and your API key, as set up in the first article of this series.
public record TokenReport(String answer, Integer promptTokens,
Integer completionTokens, Integer totalTokens) {
}
@GetMapping("/tokens")
public TokenReport tokens(@RequestParam("message") String message) {
ChatResponse response = chatClient.prompt()
.user(message)
.call()
.chatResponse();
if (response == null || response.getResult() == null) {
throw new IllegalStateException("Empty response from model");
}
Usage usage = response.getMetadata().getUsage();
return new TokenReport(
response.getResult().getOutput().getText(),
usage.getPromptTokens(),
usage.getCompletionTokens(),
usage.getTotalTokens());
}Next, try a short question and then a long one. You will see the prompt tokens grow with your input. Similarly, the completion tokens grow with the length of the answer. Both numbers show up on your bill.
Next, let us turn words into vectors and compare them. First, add the embedding model to application.properties. The same OpenAI starter also gives you an EmbeddingModel bean:
spring.ai.openai.api-key=${OPENAI_API_KEY}
spring.ai.openai.embedding.model=text-embedding-3-smallNow the controller. In Spring AI 2.0.1, embed() returns a float array:
@RestController
@RequestMapping("/api")
public class EmbeddingController {
private final EmbeddingModel embeddingModel;
public EmbeddingController(EmbeddingModel embeddingModel) {
this.embeddingModel = embeddingModel;
}
@GetMapping("/similarity")
public String similarity(@RequestParam("first") String first,
@RequestParam("second") String second) {
float[] a = embeddingModel.embed(first);
float[] b = embeddingModel.embed(second);
return "Dimensions: %d, similarity: %.3f"
.formatted(a.length, cosineSimilarity(a, b));
}
private double cosineSimilarity(float[] a, float[] b) {
double dot = 0, normA = 0, normB = 0;
for (int i = 0; i < a.length; i++) {
dot += a[i] * b[i];
normA += a[i] * a[i];
normB += b[i] * b[i];
}
return dot / (Math.sqrt(normA) * Math.sqrt(normB));
}
}Call it twice with curl:
curl "http://localhost:8080/api/similarity?first=king&second=queen" curl "http://localhost:8080/api/similarity?first=king&second=banana"
Both calls report 1,536 dimensions. More importantly, “king” and “queen” score clearly higher than “king” and “banana”. That is the same idea as our toy table, just with real numbers.
Also, the cosine maths here is exactly what a vector store like Qdrant or pgvector does during a similarity search. In real RAG code, you let the VectorStore handle it.
Knowing the terms is half the job. Meanwhile, the other half is picking the right tool for a problem. Here is a simple guide:
In practice, the best systems mix these. A payment app may use rules for validation, ML for fraud scoring and an LLM for the support chatbot.
Let me clear up a few myths that come up often in teams new to AI.
| 💡 Interview Insight A strong closing question in interviews is, “If LLMs only predict the next token, why do they seem so smart?” A good answer covers three points. First, they learned patterns from trillions of tokens. Second, embeddings place similar meanings close together. Third, attention lets each word use the right context. Together, these make next-token prediction look like understanding. |
A: They are nested layers. AI is the broad goal of making machines act smart. ML is AI that learns from data. Deep learning is ML that uses many-layer neural networks. Generative AI is deep learning that creates new content. An LLM is a generative AI model for text that predicts the next token.
A: ChatGPT is an AI application built on top of LLMs, such as OpenAI’s GPT models. The app adds the chat loop, conversation history, safety filters and the user interface. The LLM underneath only predicts the next token.
A: No. Every LLM is generative AI, but not the other way round. Image tools like Stable Diffusion use diffusion models, and older image generators used GANs. Only models that work with text are LLMs.
A: No. AI also includes rule-based systems where a developer writes every rule, such as an if-else spam filter or a chess engine with hand-written logic. Machine learning is the part of AI where the system learns patterns from data instead.
A: A token is a small piece of text, such as a word, part of a word or a single character. LLMs read and write tokens, not words. In English, one token is about three-fourths of a word, and hosted models charge you per token.
A: LLMs are used through ChatModel and ChatClient, embeddings through EmbeddingModel and VectorStore, image generation through ImageModel, and speech through TextToSpeechModel and TranscriptionModel. Token counts come from the Usage object in the ChatResponse metadata.
AI, ML, deep learning, generative AI and LLMs are not five competing technologies. They are five nested layers of the same story.
Here is a quick recap:
Under the hood, an LLM turns text into tokens, tokens into embeddings, and uses attention to understand context. In Spring AI, you meet these ideas through ChatClient, EmbeddingModel and the Usage metadata.
So once these basics are clear, topics like RAG, chat memory and tool calling become much easier. You will know exactly what problem each feature solves.