Ravindra BagaleCourses & study guides Track your progress
AI CODING ASSISTANTS · CHAPTER 3 · LANGUAGES

How to Code in Java Using AI

Use an AI assistant to write a Java method, compile and run it, and prove it with JUnit 5 tests. Works in IntelliJ, VS Code or Eclipse.

In short: say the Java version and build tool, give the method signature and rules, ask for JUnit 5 tests, run them.

Why Java with AI

WHY

Java is used in big systems at banks, telecom and e-commerce companies like Flipkart and Amazon. It needs a lot of boilerplate: classes, getters, tests. AI writes that part fast, so you focus on the logic.

What you need

WHAT
  • JDK 21 (LTS): Eclipse Temurin or another OpenJDK build. Check with java -version.
  • Build tool: Maven or Gradle. They download JUnit for you.
  • IDE + assistant: IntelliJ with GitHub Copilot, or VS Code with Copilot or Claude Code.
  • JUnit 5: the standard Java test library.

How it flows

1 · Describe the method Java 21, signature, rules 2 · AI writes code read every line 3 · Compile + run javac / green arrow 4 · Ask for JUnit tests edge cases incl. null 5 · Run tests mvn test = green

Install and check

HOW
  1. Install JDK 21 (for example Eclipse Temurin 21 from adoptium.net).
  2. Check: java -version and javac -version show 21.
  3. Install Maven, or let IntelliJ create a Maven project for you (New Project → Maven).
  4. Add JUnit 5 to pom.xml (ask the AI: “add JUnit 5 test dependency to this pom.xml”, then check the version on Maven Central).

Step 1 — the prompt

COPY THIS PROMPT

Write a Java 21 class PasswordCheck with public static boolean isStrong(String pw). Strong means at least 8 characters, one uppercase, one lowercase and one digit. Null returns false. No external libraries. Add a main method that prints the result for "Mumbai2026" and "password". Only return the code.

Step 2 — the code (tested here)

PasswordCheck.java
// Check password strength. Built with an AI assistant, then tested.
public class PasswordCheck {
    public static boolean isStrong(String pw) {
        if (pw == null || pw.length() < 8) return false;
        boolean upper = false, lower = false, digit = false;
        for (char c : pw.toCharArray()) {
            if (Character.isUpperCase(c)) upper = true;
            else if (Character.isLowerCase(c)) lower = true;
            else if (Character.isDigit(c)) digit = true;
        }
        return upper && lower && digit;
    }

    public static void main(String[] args) {
        System.out.println(isStrong("Mumbai2026"));  // true
        System.out.println(isStrong("password"));    // false
    }
}

Step 3 — compile and run

javac PasswordCheck.java
java PasswordCheck
# -> true
# -> false

Step 4 — ask for JUnit 5 tests

FOLLOW-UP PROMPT

Write JUnit 5 tests for PasswordCheck.isStrong: strong, too short, no digit, and null.

PasswordCheckTest.java
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class PasswordCheckTest {
    @Test void strongPassword() { assertTrue(PasswordCheck.isStrong("Mumbai2026")); }
    @Test void tooShort()       { assertFalse(PasswordCheck.isStrong("Ab1")); }
    @Test void noDigit()        { assertFalse(PasswordCheck.isStrong("MumbaiCity")); }
    @Test void nullIsWeak()     { assertFalse(PasswordCheck.isStrong(null)); }
}
mvn test
# -> Tests run: 4, Failures: 0

Settings and config

  1. Project rules: in .github/copilot-instructions.md or CLAUDE.md write “Java 21, Maven, JUnit 5, no new dependencies without asking”.
  2. IntelliJ: File → Project Structure → SDK = 21, so the AI's modern code (records, switch expressions) compiles.
  3. Format: Code → Reformat Code after accepting AI code, so style stays the same.

Good Java prompts (reuse these)

  1. “Turn this class into a Java record.”
  2. “Add null checks and throw IllegalArgumentException with a clear message.”
  3. “Replace this for loop with a stream, same behaviour, and keep the tests passing.”
  4. “Explain this stack trace and fix it:” + paste only the top lines.

Watch out (common AI mistakes in Java)

  • JUnit 4 vs 5 mix-up — org.junit.Test is JUnit 4; JUnit 5 uses org.junit.jupiter.api.Test.
  • Wrong dependency versions — check on Maven Central.
  • Null handling — always test null input.
  • Old Java — code for Java 8 is fine, but say your version so it can use newer features safely.

Try this yourself: ask AI for a GST total in Java, then prove the cases

Hello friends. The live chapter already walked through PasswordCheck with JUnit 5. This practice is a different fictional shop called Fable Mart. You ask an AI for a Java class GstInvoice with totalWithGst for GST line totals, add validation for negatives and bad rates, and prove the numbers. We compiled the Java code for Java 17, ran the JUnit 5 tests with the JUnit console launcher, and also ran a tiny Python behavioral twin under pytest. On your own machine, you can run the same JUnit 5 test file through Maven or your IDE.

Ravindra Bagale's Tip

Say the Java version in your prompt, ask for IllegalArgumentException messages you can assert, and keep a small table of expected totals such as 100 at 18 percent equals 118.00. Compile with javac when you can, and keep JUnit 5 cases even if you first prove the same numbers with another language twin.

Practice label: Fable Mart, every rupee amount and every GST rate here is fictional teaching data. It is not a real shop or tax filing. Passing these tests proves only the listed cases.
Environment (tested): on 16 November 2026 this exercise was re-run with OpenJDK 21.0.13 using javac --release 17, so the code stays Java 17 compatible. The fixed GstInvoice.main printed 118.0 and 263.03. The JUnit 5 file GstInvoiceTest.java was run with the JUnit Platform Console Launcher 1.11.4: the starter class had 2 failed and 3 passed tests, and the fixed class had 5 passed tests. The Python twin passed 6 tests under Python 3.13.5 and pytest 9.1.1, and the buggy twin had 3 failed and 3 passed.

Your task: start from the buggy GstInvoice.java that calculates a total but skips validation. Ask an AI to add finite checks, reject negative taxable amounts, reject rates outside 0..100, and round half-up to two decimals. Keep the JUnit 5 file for your machine. On machines without Maven yet, you may also use the Python twin and test_gst_invoice.py to prove the same numbers.

Setup

HOW
  1. Create a project folder and open a terminal inside it.
  2. Create a virtual environment: on macOS or Linux run python3 -m venv .venv. On Windows run py -3 -m venv .venv.
  3. Activate it: on macOS or Linux run source .venv/bin/activate. In Windows Command Prompt run .venv\Scripts\activate.bat, and in Windows PowerShell run .venv\Scripts\Activate.ps1.
  4. Install pytest inside the virtual environment: python -m pip install pytest.

Extra for Java on your machine: install JDK 17 or newer, confirm java -version and javac -version, and run JUnit 5 through Maven or your IDE.

Starter GstInvoice.java (computes totals, skips validation):

GstInvoice.java
/**
 * Fable Mart GST line total (fictional teaching shop — not a real business).
 * Starter: computes a total but skips validation. Ask an AI to add the checks,
 * then prove with JUnit / the Python twin.
 */
public final class GstInvoice {
    private GstInvoice() {}

    public static double totalWithGst(double taxableRupees, double ratePercent) {
        // Starter bug: no validation for negatives, NaN, or rate range.
        double raw = taxableRupees * (1.0 + ratePercent / 100.0);
        return Math.round(raw * 100.0) / 100.0;
    }

    public static void main(String[] args) {
        System.out.println(totalWithGst(100.0, 18.0));
    }
}

JUnit 5 tests GstInvoiceTest.java (for your Maven or IDE run later):

GstInvoiceTest.java
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

/** JUnit 5 cases for fictional Fable Mart GstInvoice (run with Maven/Gradle on your machine). */
class GstInvoiceTest {
    @Test void eighteenPercentOnHundred() {
        assertEquals(118.0, GstInvoice.totalWithGst(100.0, 18.0), 0.0001);
    }

    @Test void fivePercentOnTwoFiftyPointFive() {
        assertEquals(263.03, GstInvoice.totalWithGst(250.5, 5.0), 0.0001);
    }

    @Test void zeroRateKeepsTaxable() {
        assertEquals(40.0, GstInvoice.totalWithGst(40.0, 0.0), 0.0001);
    }

    @Test void rejectsNegativeTaxable() {
        IllegalArgumentException ex = assertThrows(
            IllegalArgumentException.class,
            () -> GstInvoice.totalWithGst(-1.0, 18.0)
        );
        assertTrue(ex.getMessage().contains("negative"));
    }

    @Test void rejectsRateAboveOneHundred() {
        IllegalArgumentException ex = assertThrows(
            IllegalArgumentException.class,
            () -> GstInvoice.totalWithGst(10.0, 101.0)
        );
        assertTrue(ex.getMessage().contains("0 and 100"));
    }
}

Python twin gst_invoice.py (optional local proof matching the same cases):

gst_invoice.py
"""Behavioral twin of GstInvoice.totalWithGst for local pytest without a full Maven run."""
from __future__ import annotations

import math


def _round_half_up_2(value: float) -> float:
    """Match Java Math.round on non-negative values (half away from zero toward +inf)."""
    return math.floor(value * 100.0 + 0.5) / 100.0


def total_with_gst(taxable_rupees: float, rate_percent: float) -> float:
    """Mirror of GstInvoice.totalWithGst (fictional Fable Mart teaching data)."""
    if not isinstance(taxable_rupees, (int, float)) or isinstance(taxable_rupees, bool):
        raise TypeError("taxable_rupees must be a number")
    if not isinstance(rate_percent, (int, float)) or isinstance(rate_percent, bool):
        raise TypeError("rate_percent must be a number")
    if not math.isfinite(taxable_rupees) or not math.isfinite(rate_percent):
        raise ValueError("taxable and rate must be finite numbers")
    if taxable_rupees < 0:
        raise ValueError("taxable must not be negative")
    if rate_percent < 0 or rate_percent > 100:
        raise ValueError("ratePercent must be between 0 and 100")
    raw = taxable_rupees * (1.0 + rate_percent / 100.0)
    return _round_half_up_2(raw)

pytest twin test_gst_invoice.py:

test_gst_invoice.py
"""pytest twin for fictional Fable Mart GstInvoice cases (same numbers as JUnit)."""
import math
import pytest
from gst_invoice import total_with_gst


def test_eighteen_percent_on_hundred():
    assert total_with_gst(100.0, 18.0) == 118.0


def test_five_percent_on_250_5():
    assert total_with_gst(250.5, 5.0) == 263.03


def test_zero_rate_keeps_taxable():
    assert total_with_gst(40.0, 0.0) == 40.0


def test_rejects_negative_taxable():
    with pytest.raises(ValueError, match="negative"):
        total_with_gst(-1.0, 18.0)


def test_rejects_rate_above_one_hundred():
    with pytest.raises(ValueError, match="0 and 100"):
        total_with_gst(10.0, 101.0)


def test_rejects_non_finite():
    with pytest.raises(ValueError, match="finite"):
        total_with_gst(float("nan"), 18.0)

Suggested AI ask (copy and adapt):

java-prompt.txt
Write a Java 17 final class GstInvoice with public static double totalWithGst(double taxableRupees, double ratePercent). Reject NaN and infinite inputs with IllegalArgumentException mentioning finite. Reject negative taxable with message containing negative. Reject ratePercent outside 0..100 with message containing 0 and 100. Return taxable plus GST rounded half-up to two decimals using Math.round on value times 100. Add a main that prints totalWithGst(100.0, 18.0) and totalWithGst(250.5, 5.0). Fictional Fable Mart teaching only. Also draft JUnit 5 tests for those cases plus zero rate.

HOW to finish

HOW
  1. Save the starter Java file, the JUnit file, and optionally the Python twin files.
  2. Ask your AI assistant to add validation and keep the rounding behaviour.
  3. Compile when you have a JDK: javac GstInvoice.java then java GstInvoice. Expect lines 118.0 and 263.03.
  4. Run JUnit 5 with Maven or your IDE on your machine.
  5. Optional twin: python -m pytest -q test_gst_invoice.py with the fixed Python twin. Expect 6 passed. The buggy twin was measured here as 3 failed, 3 passed.

Real javac and main output on this box:

java-main.txt
118.0
263.03

Real pytest twin output after the fixed Python mirror:

pytest-after.txt
......                                                                   [100%]
6 passed in 0.01s
Optional completed GstInvoice.java (try it yourself first)

Your AI assistant may reorder the checks. Any version is fine if javac succeeds, main prints the two totals, and the JUnit or pytest twin cases pass.

GstInvoice.java
/**
 * Fable Mart GST line total (fictional teaching shop — not a real business).
 * Students ask an AI for this class, then prove cases with JUnit (and/or the Python twin).
 */
public final class GstInvoice {
    private GstInvoice() {}

    /**
     * Return taxable + GST, rounded to 2 decimal places using half-up style via long math.
     *
     * @param taxableRupees amount before tax; must be >= 0
     * @param ratePercent GST rate such as 0, 5, 12, or 18
     * @return total including GST
     * @throws IllegalArgumentException when taxable is negative or rate is outside 0..100
     */
    public static double totalWithGst(double taxableRupees, double ratePercent) {
        if (Double.isNaN(taxableRupees) || Double.isInfinite(taxableRupees)
                || Double.isNaN(ratePercent) || Double.isInfinite(ratePercent)) {
            throw new IllegalArgumentException("taxable and rate must be finite numbers");
        }
        if (taxableRupees < 0) {
            throw new IllegalArgumentException("taxable must not be negative");
        }
        if (ratePercent < 0 || ratePercent > 100) {
            throw new IllegalArgumentException("ratePercent must be between 0 and 100");
        }
        double raw = taxableRupees * (1.0 + ratePercent / 100.0);
        return Math.round(raw * 100.0) / 100.0;
    }

    public static void main(String[] args) {
        System.out.println(totalWithGst(100.0, 18.0));
        System.out.println(totalWithGst(250.5, 5.0));
    }
}

Troubleshooting

HOW
  1. Problem: 250.5 at 5 percent becomes 263.02 in Python. Fix: Java Math.round is half-up for this positive case. Mirror that rounding in any twin, or trust the Java result and the JUnit expectation 263.03.
  2. Error: javac: command not found. Fix: install a JDK 17 or newer, or use your IDE build. After installing, open a new terminal so the updated PATH is picked up, and check javac -version again.
  3. Problem: JUnit imports fail. Fix: use org.junit.jupiter.api.Test for JUnit 5, not the JUnit 4 org.junit.Test package.
  4. Problem: negative taxable still returns a number. Fix: throw IllegalArgumentException before the multiply, with a message that contains negative.

Practice cards: English and spoken Marathi

Each card below explains one idea on its own, so you can save or revise a single card without reading the whole chapter.

PRACTICE CARDAI Coding

Name the Java version in the prompt

Ask for GstInvoice.totalWithGst with clear IllegalArgumentException rules.
Compile, then prove 100 at 18 percent equals 118.00 and 250.5 at 5 percent equals 263.03.
Ravindra Bagale · ravindrabagale.com/ai-coding
PRACTICE CARDAI Coding

Keep JUnit even if you use a twin

A Python twin can prove the same numbers when Maven is not ready yet.
Still save GstInvoiceTest.java so your Java toolchain remains the source of truth.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

Prompt मध्ये Java version सांगा

स्पष्ट IllegalArgumentException नियम असलेले GstInvoice.totalWithGst मागा.
Compile करा, नंतर 100 वर 18 percent म्हणजे 118.00 आणि 250.5 वर 5 percent म्हणजे 263.03 सिद्ध करा.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

Twin वापरला तरी JUnit ठेवा

Maven तयार नसताना Python twin समान आकडे सिद्ध करू शकतो.
तरी GstInvoiceTest.java जपून ठेवा, जेणेकरून Java toolchainच स्रोत सत्य राहील.
Ravindra Bagale · ravindrabagale.com/ai-coding

Quick quiz

1. Which test library does this chapter use?

JUnit 5 (org.junit.jupiter).

2. What does isStrong("Mumbai2026") return?

true.

3. How do you run Maven tests?

mvn test.

4. Common AI mistake with JUnit imports?

Mixing JUnit 4 org.junit.Test with JUnit 5.

Save tokens and money

SMART AI USE

Paste one class, not the whole project or target/ folder. Paste only the top 10 lines of a stack trace. Let IntelliJ generate getters and constructors for free (Alt+Insert) instead of asking the AI.

Save these cards

INTERVIEW CARDAI Coding

How do you use AI safely for Java?

Give version + build tool + signature + rules.
Compile, then prove with JUnit 5 tests.
Ravindra Bagale · ravindrabagale.com/ai-coding
COMPARISON CARDAI Coding

IDE generate vs AI generate

IDE (Alt+Insert): getters, constructors, free and exact.
AI: logic, tests, refactors. Needs review.
Ravindra Bagale · ravindrabagale.com/ai-coding
REVISION CARDAI Coding

Java with AI in 3

Java 21 + Maven + JUnit 5 in the prompt.
Test null and edge cases.
mvn test = proof.
Ravindra Bagale · ravindrabagale.com/ai-coding