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
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
- 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
Install and check
- Install JDK 21 (for example Eclipse Temurin 21 from adoptium.net).
- Check:
java -versionandjavac -versionshow 21. - Install Maven, or let IntelliJ create a Maven project for you (New Project → Maven).
- 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
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
# -> falseStep 4 — ask for JUnit 5 tests
Write JUnit 5 tests for PasswordCheck.isStrong: strong, too short, no digit, and null.
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: 0Settings and config
- Project rules: in
.github/copilot-instructions.mdorCLAUDE.mdwrite “Java 21, Maven, JUnit 5, no new dependencies without asking”. - IntelliJ: File → Project Structure → SDK = 21, so the AI's modern code (records, switch expressions) compiles.
- Format: Code → Reformat Code after accepting AI code, so style stays the same.
Good Java prompts (reuse these)
- “Turn this class into a Java record.”
- “Add null checks and throw IllegalArgumentException with a clear message.”
- “Replace this for loop with a stream, same behaviour, and keep the tests passing.”
- “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.Testis JUnit 4; JUnit 5 usesorg.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.
नमस्कार मित्रांनो. Live chapter मध्ये PasswordCheck आणि JUnit 5 आधीच आले आहे. हा सराव Fable Mart नावाच्या वेगळ्या काल्पनिक दुकानावर आहे. तुम्ही AI कडून GstInvoice Java class मागता ज्यात totalWithGst GST line totals काढते, negatives आणि चुकीच्या rates साठी validation जोडता, आणि आकडे सिद्ध करता. आम्ही Java code Java 17 साठी compile केला, JUnit console launcher ने JUnit 5 tests चालवल्या, आणि छोटा Python behavioral twin pytest ने पण चालवला. तुमच्या मशीनवर तीच JUnit 5 test file Maven किंवा IDE मधून चालवू शकता.
नमस्ते दोस्तों. Live chapter में PasswordCheck और JUnit 5 पहले आ चुके हैं. यह अभ्यास Fable Mart नाम की अलग काल्पनिक दुकान पर है. आप AI से GstInvoice Java class मांगते हो जिसमें totalWithGst GST line totals निकाले, negatives और गलत rates के लिए validation जोड़ते हो, और आंकड़े साबित करते हो. हमने Java code को Java 17 के लिए compile किया, JUnit console launcher से JUnit 5 tests चलाए, और छोटा Python behavioral twin pytest से भी चलाया. अपनी मशीन पर वही JUnit 5 test file Maven या 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.
Ravindra Bagale's Tip – मराठी
Prompt मध्ये Java version सांगा, assert करता येतील अशी IllegalArgumentException messages मागा, आणि 100 वर 18 percent म्हणजे 118.00 सारखी छोटी expected totals ची table ठेवा. शक्य असेल तेव्हा javac ने compile करा, आणि दुसऱ्या language twin ने आधी सिद्ध केले तरी JUnit 5 cases जपून ठेवा.
Ravindra Bagale's Tip – हिंदी
Prompt में Java version बताओ, ऐसी IllegalArgumentException messages मांगो जिन पर assert हो सके, और 100 पर 18 percent यानी 118.00 जैसी छोटी expected totals की table रखो. जब हो सके javac से compile करो, और दूसरी language twin से पहले साबित करने पर भी JUnit 5 cases बचाए रखो।
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
- Create a project folder and open a terminal inside it.
- Create a virtual environment: on macOS or Linux run
python3 -m venv .venv. On Windows runpy -3 -m venv .venv. - 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. - 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):
/**
* 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):
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):
"""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:
"""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.txtWrite 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
- Save the starter Java file, the JUnit file, and optionally the Python twin files.
- Ask your AI assistant to add validation and keep the rounding behaviour.
- Compile when you have a JDK:
javac GstInvoice.javathenjava GstInvoice. Expect lines118.0and263.03. - Run JUnit 5 with Maven or your IDE on your machine.
- Optional twin:
python -m pytest -q test_gst_invoice.pywith 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.txt118.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
- Problem:
250.5at 5 percent becomes263.02in Python. Fix: JavaMath.roundis half-up for this positive case. Mirror that rounding in any twin, or trust the Java result and the JUnit expectation263.03. - 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 checkjavac -versionagain. - Problem: JUnit imports fail. Fix: use
org.junit.jupiter.api.Testfor JUnit 5, not the JUnit 4org.junit.Testpackage. - Problem: negative taxable still returns a number. Fix: throw
IllegalArgumentExceptionbefore the multiply, with a message that containsnegative.
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.
Name the Java version in the prompt
Keep JUnit even if you use a twin
Prompt मध्ये Java version सांगा
Twin वापरला तरी JUnit ठेवा
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
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.