Using the Google Gemini Large Language Model APIs in Java
This example is very similar to OpenAI API examples in the previous chapter. We use the Google Developer’s documentation as a reference: https://ai.google.dev/gemini-api/docs. We implement methods for completions and completions also using Google’s search tool.
Java Library to Use OpenAI’s APIs
The library code defined in the directory Java-AI-Book-Code/gemini-llm-client is designed to interact with the Gemini API to accept a prompt string and get a text completion. Here’s a breakdown of what each part of the code does:
CLASS: com.markwatson.gemini.GeminiCompletions
Provides a set of static methods for interacting with the Google Gemini API and for performing related string and file utility operations.
FUNCTION: getCompletion(String prompt)
Sends a text prompt to the Gemini API and returns the generated text completion.
-
INPUT:
- A String ‘prompt’.
-
REQUIRES:
- The ‘GOOGLE_API_KEY’ environment variable must be set.
-
ACTION:
- Constructs an HTTP POST request to the ‘gemini-3-flash-preview’ model endpoint.
- Packages the prompt into the required JSON body.
-
ON SUCCESS:
- Returns the ‘text’ field from the API’s JSON response as a String.
-
ON FAILURE:
- Throws an IOException if the API key is not found.
FUNCTION: getCompletionWithSearch(String prompt)
Sends a text prompt to the Gemini API using the search tool and returns the generated text completion.
-
INPUT:
- A String ‘prompt’.
-
REQUIRES:
- The ‘GOOGLE_API_KEY’ environment variable must be set.
-
ACTION:
- Constructs an HTTP POST request to the ‘gemini-3-flash-preview’ model endpoint.
- Packages the prompt into the required JSON body.
-
ON SUCCESS:
- Returns the ‘text’ field from the API’s JSON response as a String.
-
ON FAILURE:
- Throws an IOException if the API key is not found.
FUNCTION: readFileToString(String filePath)
Reads the entire contents of a specified file into a single string.
-
INPUT:
- A String ‘filePath’ pointing to a file.
-
ACTION:
- Reads all bytes from the file.
- Escapes all double-quote (“) characters found in the content.
-
ON SUCCESS:
- Returns the file’s contents as a String.
-
ON FAILURE:
- Throws an IOException if the file cannot be found or read.
FUNCTION: replaceSubstring(…)
A utility function that replaces all occurrences of a substring within a string.
-
INPUT:
- An original string.
- The substring to replace.
- The replacement string.
-
OUTPUT:
- Returns the new string with replacements made.
FUNCTION: promptVar(…)
A simple templating utility for substituting a placeholder in a string.
-
INPUT:
- A template string.
- A placeholder name to find.
- The value to substitute.
-
OUTPUT:
- Returns the new string with the placeholder replaced by the value.
Code Listing
1 package com.markwatson.gemini;
2
3 import org.json.JSONObject;
4
5 import java.io.BufferedReader;
6 import java.io.IOException;
7 import java.io.InputStreamReader;
8 import java.io.OutputStream;
9 import java.net.HttpURLConnection;
10 import java.net.URI;
11 import java.net.URL;
12 import java.net.URLConnection;
13 import java.nio.file.Files;
14 import java.nio.file.Path;
15 import java.nio.file.Paths;
16
17 public class GeminiCompletions {
18
19 public static String model = "gemini-3-flash-preview";
20
21 public static void main(String[] args) throws Exception {
22 String prompt = "How much is 11 + 22?";
23 String completion = getCompletion(prompt);
24 System.out.println("completion: " + completion);
25 }
26
27 public static String getCompletion(String prompt) throws Exception {
28 String jsonBody = "{\"contents\":[{\"parts\":[{\"text\":\"" + prompt + "\"}]}]}";
29 return executeRequest(jsonBody);
30 }
31
32 public static String getCompletionWithSearch(String prompt) throws Exception {
33 String jsonBody = "{\"contents\":[{\"parts\":[{\"text\":\"" + prompt
34 + "\"}]}],\"tools\":[{\"google_search\":{}}]}";
35 return executeRequest(jsonBody);
36 }
37
38 private static String executeRequest(String jsonBody) throws Exception {
39 String apiKey = System.getenv("GOOGLE_API_KEY");
40 if (apiKey == null || apiKey.isEmpty()) {
41 throw new IOException("GOOGLE_API_KEY environment variable not set.");
42 }
43 URI uri = new URI(
44 "https://generativelanguage.googleapis.com/v1beta/models/" + model + ":generateContent?key=" + apiKey);
45 URL url = uri.toURL();
46
47 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
48 connection.setRequestMethod("POST");
49 connection.setRequestProperty("Content-Type", "application/json");
50 connection.setDoOutput(true);
51 try (OutputStream os = connection.getOutputStream()) {
52 byte[] input = jsonBody.getBytes("utf-8");
53 os.write(input, 0, input.length);
54 }
55
56 StringBuilder response = new StringBuilder();
57 try (BufferedReader br = new BufferedReader(
58 new InputStreamReader(connection.getInputStream(), "utf-8"))) {
59 String responseLine = null;
60 while ((responseLine = br.readLine()) != null) {
61 response.append(responseLine.trim());
62 }
63 }
64
65 connection.disconnect();
66 JSONObject jsonObject = new JSONObject(response.toString());
67 return jsonObject.getJSONArray("candidates").getJSONObject(0).getJSONObject("content").getJSONArray("parts")
68 .getJSONObject(0).getString("text");
69 }
70
71
72 /***
73 * Utilities for using the Gemini API
74 */
75
76 // read the contents of a file path into a Java string
77 public static String readFileToString(String filePath) throws IOException {
78 Path path = Paths.get(filePath);
79 return new String(Files.readAllBytes(path)).replace("\"", "\\\"");
80 }
81
82 public static String replaceSubstring(String originalString, String substringToReplace, String replacementString) {
83 return originalString.replace(substringToReplace, replacementString);
84 }
85 public static String promptVar(String prompt0, String varName, String varValue) {
86 String prompt = replaceSubstring(prompt0, varName, varValue);
87 return replaceSubstring(prompt, varName, varValue);
88 }
89 }
In the next section we write a unit test for this Java class to demonstrate text completion.
Example Applications
Here are unit tests provided with this library that shows how to call each API:
1 public void testCompletion() throws Exception {
2 String r = GeminiCompletions
3 .getCompletion("Translate the following English text to French: 'Hello, how are you?'");
4 System.out.println("completion: " + r);
5 assertTrue(true);
6 }
7
8 public void testTwoShotTemplate() throws Exception {
9 String input_text = "Mark Johnson enjoys living in Berkeley California at 102 Dunston Street and use mjess@foobar.com for contacting him.";
10 String prompt0 = GeminiCompletions.readFileToString("../prompts/two-shot-2-var.txt");
11 System.out.println("prompt0: " + prompt0);
12 String prompt = GeminiCompletions.promptVar(prompt0, "{input_text}", input_text);
13 System.out.println("prompt: " + prompt);
14 String r = GeminiCompletions.getCompletion(prompt);
15 System.out.println("two shot extraction completion: " + r);
16 assertTrue(true);
17 }
18
19 public void testSummarization() throws Exception {
20 String input_text = "Jupiter is the fifth planet from the Sun and the largest in the Solar System. It is a gas giant with a mass one-thousandth that of the Sun, but two-and-a-half times that of all the other planets in the Solar System combined. Jupiter is one of the brightest objects visible to the naked eye in the night sky, and has been known to ancient civilizations since before recorded history. It is named after the Roman god Jupiter.[19] When viewed from Earth, Jupiter can be bright enough for its reflected light to cast visible shadows,[ and is on average the third-brightest natural object in the night sky after the Moon and Venus.";
21 String prompt0 = GeminiCompletions.readFileToString("../prompts/summarization_prompt.txt");
22 System.out.println("prompt0: " + prompt0);
23 String prompt = GeminiCompletions.promptVar(prompt0, "{input_text}", input_text);
24 System.out.println("prompt: " + prompt);
25 String r = GeminiCompletions.getCompletion(prompt);
26 System.out.println("summarization completion: " + r);
27 assertTrue(true);
28 }
29
30 public void testCompletionWithSearch() throws Exception {
31 String prompt = "What is the current stock price of Google?";
32 String r = GeminiCompletions.getCompletionWithSearch(prompt);
33 System.out.println("Search completion: " + r);
34 assertNotNull(r);
35 assertFalse(r.isEmpty());
36 }
Sample output is:
1 $ make
2 mvn test -q # run test in quiet mode
3 completion: Here are a few ways to say this in French, depending on the level of formality:
4
5 * **Formal/Standard:** *Bonjour, comment allez-vous ?*
6 * **Informal/Casual:** *Salut, ça va ?*
7 * **Neutral:** *Bonjour, comment ça va ?*
8
9 Search completion: As of the market close on December 18, 2025, the stock prices for **Alphabet Inc. (Google)** are as follows:
10
11 * **Alphabet Inc. Class A (GOOGL):** ~$302.01
12 * **Alphabet Inc. Class C (GOOG):** ~$303.29
13
14
15 prompt0: Given the two examples below, extract the names, addresses, and email addresses of individuals mentioned later as Process Text. Format the extracted information in JSON, with keys for \"name\", \"address\", and \"email\". If any information is missing, use \"null\" for that field. Be very concise in your output by providing only the output JSON.
16
17 Example 1:
18 Text: \"John Doe lives at 1234 Maple Street, Springfield. His email is johndoe@example.com.\"
19 Output:
20 {
21 \"name\": \"John Doe\",
22 \"address\": \"1234 Maple Street, Springfield\",
23 \"email\": \"johndoe@example.com\"
24 }
25
26 Example 2:
27 Text: \"Jane Smith has recently moved to 5678 Oak Avenue, Anytown. She hasn't updated her email yet.\"
28 Output:
29 {
30 \"name\": \"Jane Smith\",
31 \"address\": \"5678 Oak Avenue, Anytown\",
32 \"email\": null
33 }
34
35 Process Text: \"{input_text}\"
36 Output:
37
38 prompt: Given the two examples below, extract the names, addresses, and email addresses of individuals mentioned later as Process Text. Format the extracted information in JSON, with keys for \"name\", \"address\", and \"email\". If any information is missing, use \"null\" for that field. Be very concise in your output by providing only the output JSON.
39
40 Example 1:
41 Text: \"John Doe lives at 1234 Maple Street, Springfield. His email is johndoe@example.com.\"
42 Output:
43 {
44 \"name\": \"John Doe\",
45 \"address\": \"1234 Maple Street, Springfield\",
46 \"email\": \"johndoe@example.com\"
47 }
48
49 Example 2:
50 Text: \"Jane Smith has recently moved to 5678 Oak Avenue, Anytown. She hasn't updated her email yet.\"
51 Output:
52 {
53 \"name\": \"Jane Smith\",
54 \"address\": \"5678 Oak Avenue, Anytown\",
55 \"email\": null
56 }
57
58 Process Text: \"Mark Johnson enjoys living in Berkeley California at 102 Dunston Street and use mjess@foobar.com for contacting him.\"
59 Output:
60
61 two shot extraction completion: {
62 "name": "Mark Johnson",
63 "address": "102 Dunston Street, Berkeley California",
64 "email": "mjess@foobar.com"
65 }
66 prompt0: Summarize the following text: \"{input_text}\"
67 Output:
68
69 prompt: Summarize the following text: \"Jupiter is the fifth planet from the Sun and the largest in the Solar System. It is a gas giant with a mass one-thousandth that of the Sun, but two-and-a-half times that of all the other planets in the Solar System combined. Jupiter is one of the brightest objects visible to the naked eye in the night sky, and has been known to ancient civilizations since before recorded history. It is named after the Roman god Jupiter.[19] When viewed from Earth, Jupiter can be bright enough for its reflected light to cast visible shadows,[ and is on average the third-brightest natural object in the night sky after the Moon and Venus.\"
70 Output:
71
72 summarization completion: Jupiter is the fifth planet from the Sun and the largest in the Solar System. A gas giant named after the Roman god, it is more massive than all other planets combined and stands as the third-brightest natural object in the night sky.
Wrap Up
The Java test code for the Gemini API also contains two more complex examples, similar to what was listed in the last chapter for OpenAI API support.