COBOL to Java with AI: How to Ship Clean Code, Not Just Passing Tests
Six AI models matched 41,918-line Medicare COBOL to the penny, yet only one wrote maintainable Java.
Before you spend money migrating COBOL with AI, four findings should shape your plan:
- Exact COBOL translation is no longer the hard part. All six matched 41,918-line Medicare COBOL to the cent without a compiler; quality, tests, and cost now decide.
- AI extracts complex rules accurately, yet most models skip rule tests. All six recovered Medicare rules, yet only
Gemini 4 Neonand agenticArgontested all 10 policy areas. - AI token bills are tiny compared to testing and review. Raw API costs for 10 million lines scale to roughly
$1,540, so human review drives real budgets. - Use two models in sequence, not one. Run
GPT-6.1 Solfirst for a cheap test baseline, then haveGemini 4 Neonwrite clean Java.
We tested six models on three US Medicare COBOL programs totaling 50,245 lines. The smallest programs are FQHC at 1,772 lines and Hospice at 6,555 lines. The main stress test is OPPS, a 41,918-line hospital payment calculator.
Our lineup covers Gemini 4 Neon, Argon, and Carbon; Claude Opus 5.5 and Sonnet 5.5; and GPT-6.1 Sol. Every model worked inside an offline container with no access to a COBOL compiler. We checked each Java build against compiled COBOL on 60 hidden claims, requiring an exact $0.00 match.
Your team can run the verification gates inside an offline Docker container in its own CI. The output is standard Java 17 and JUnit 5, with no proprietary runtime.
We tested every model in two modes:
- One-shot (single prompt): The model sees the COBOL files once, with no tools and no retries. It must write the entire Java project in one reply.
- Agentic (coding loop): The model uses shell, file-editor, and Java build tools across multiple turns. It reads files in pieces, compiles Java, runs unit tests, and fixes errors, still without a COBOL compiler.
On the large OPPS program, we also checked 119 unseen test claims and external rate updates. Then three rival AI labs scored every passing Java codebase blindly to judge long-term maintainability.
1. Which AI Model Should Your Team Choose?
Most teams expect getting exact outputs from 41,918-line COBOL to be the hardest hurdle. Inside a coding loop, all six models cleared that hurdle and matched 60 of 60 hidden OPPS claims. They also matched at least 118 of 119 unseen test claims without running a COBOL compiler.
Because every model gets the right answer, pass rate hides huge gaps in cost and code quality. Instead, pick each model for a specific job in your migration plan:
- Choose
Gemini 4 Neonfor maintainable Java. It earned a unanimous 9 out of 10 from blind reviewers onOPPS. - Choose
GPT-6.1 Solfor speed and lowest cost. It finishedOPPSin 13 minutes with exact accuracy. - Choose
Gemini 4 Argonif you must convert in one prompt. It was the only model to passOPPSin a single shot.
Single-prompt conversion works well on small programs under 7,000 lines. Five of six models matched nearly every claim on FQHC and Hospice in one shot. Above 10,000 lines, single-prompt conversion breaks down because models hit token and thinking limits.
On 41,918-line OPPS, five models failed single-shot runs even though they understood COBOL fine. Both Claude models overflowed their context limit, while Neon and Carbon spent their output limits on thinking. Give your models an iterative loop with shell and build tools instead of chasing bigger single prompts.
Recent benchmarks like COBOLEval, COBOLCodeBench, and AlphaTrans confirm that single prompts fail on large legacy code. In those studies, build and test loops fixed most bugs, even when older models struggled to compile. Today's agents match 42,000-line systems without a compiler, shifting your choice from pass rate to quality and cost.
2. Can AI Accurately Extract Business Rules and Verifiable Invariants?
Yes, AI can accurately extract complex legacy rules, with two important catches for production teams. All six coding agents read 41,918 lines of Medicare COBOL and recovered dozens of interacting payment rules. They captured wage floors, outmigration adjustments, 7.1% rural hospital boosts, blood deductibles, device credits, and outlier caps.
They also recovered nine discount factors and claim validation logic covering error codes 30 through 54. With no compiler, every agent matched 60 of 60 hidden claims to the exact cent. Across claims from 2008 through 2021, every agent matched at least 118 of 119 unseen cases.
Single-shot runs still miss subtle edge rules even on small files. On 1,772-line FQHC, Claude Opus 5.5 missed one Claim 51 day limit, returning the wrong error code.
Ambiguous mainframe rules also require human decisions rather than automated guesses. On bill types '14A' through '149', Neon and Argon kept mainframe intent while four models matched Linux.
When your last COBOL maintainer retires, a slide deck of rules will not protect production. Teams need signed-off business rules and executable tests tied to working Java. This study graded working Java and unit tests rather than a standalone generated rulebook.
Catch 1: Most models fail to write executable tests proving each extracted rule. In healthcare or finance, auditors need executable tests proving every individual business rule. Only Gemini 4 Neon and agentic Argon wrote targeted tests covering all 10 Medicare policy areas:
- All 10 policy areas:
Gemini 4 Neonwrote 16 tests with 54% branch coverage. AgenticGemini 4 Argonwrote 10 tests with 56% branch coverage. - Six of 10 policy areas:
GPT-6.1 Solwrote 14 tests, reaching 25% branch coverage. - Two of 10 policy areas:
Claude Opus 5.5reached 18% branch coverage, whileClaude Sonnet 5.5reached 5%. Even blindedOpus 5.5flagged that its own submission lacked targeted domain tests.
Catch 2: Extracted rules stay useful only if your team can update rates and logic safely. We raised external Medicare rate files by 10% on disk to verify clean separation from pricing rules. Four of seven passing builds ignored those disk updates because bundled JAR files took priority.
Only Neon, Opus 5.5, and single-shot Argon passed all 60 updated claims. Sol and Sonnet 5.5 buried extracted rules inside roughly 14,500 lines across eight copy-pasted yearly files.
Only Gemini 4 Neon isolated those rules into 21 small classes. Three rival AI labs scored all seven passing builds blindly and agreed almost identically. They gave Neon a unanimous 9 out of 10, though architects must still review its shared fields.
Recent modernization studies like AgentModernize and LegacyModernize-8 confirm this exact split. Multi-agent workflows now reach over 90% rule recall, proving code structure and tests are your real bottleneck. Dual-migration tools like Syzygy and specification-graph pipelines close that gap by generating reviewable rule specs and tests per module.
Figure 3 scales five passing OPPS builds to exact size so you can see where rules live. Click any row to read the real Java each model wrote.
OPPSCAL.cob = 41,918 LOC. Every bar is scaled 1:1 to exact total Java lines (0 to 16,000); each slice is one .java file. Hover for details or click any row to inspect its source below.#0f766e) are cohesive modules (<1,500 lines); deep slate segments (#1e293b) are large monolith engines (≥1,500 lines); crimson segments (#c8372d) are duplicated per-year transpiler copies (2014–2021).
Read the Generated Java Yourself
3. What Will Extraction Actually Cost Your Team?
AI token bills are no longer the main cost of leaving a mainframe. Because prompt caches reused over 93% of input tokens, converting OPPS cost $1.15 on Sol. Getting clean, modular Java from Gemini 4 Neon cost just $5.33 for the entire program.
Combining both models averages about $0.15 per 1,000 lines of COBOL. Scaled linearly to a 10-million-line bank mainframe, raw API bills total roughly $1,540. That estimate covers raw API compute only and excludes engineering, testing, and integration labor.
In practice, raw AI compute now costs less than two days of one senior engineer. Spend your real budget on verification harnesses, domain sign-off, and rollout governance.
Paying more per token does not guarantee better Java. Claude Opus 5.5 cost $12.69 on OPPS, which is 11 times more than GPT-6.1 Sol. With Claude Opus 5.5, you pay more than double Gemini 4 Neon and get worse code. Even Claude Sonnet 5.5 cost more than GPT-6.1 Sol while scoring lowest overall.
Half of that extra cost comes from how each vendor splits legacy text into tokens. Mainframe COBOL packs files with comment stars and blank spacing. On the exact same OPPS file, Anthropic billed 1.86 times more tokens than OpenAI.
That overhead cuts a 1-million-token window nearly in half, breaking both Claude single-shot runs. The same penalty hits modern code too, where Anthropic billed 1.79 times more tokens on Java. Strip legacy comment banners before sending files to an AI model, or choose a compact tokenizer.
Recent 2024–2026 tokenization studies explain why mainframe formatting inflates your API bills. Standard tokenizers split COBOL verbs, hyphens, and spacing into 1.8 to 3.5 times more tokens than modern code. Those studies show stripping comment banners and sequence numbers cuts token and reasoning overhead by 25% to 50%.
4. What Is the Best Workflow for Migrating Legacy Code?
Do not ask one AI model to uncover legacy rules and design clean architecture together. From the same prompt, GPT-6.1 Sol acted like a compiler writer and built a fast transpiler. Gemini 4 Neon acted like a senior Java architect and refactored the rules into clean classes.
Recent migration research—including AlphaTrans (call-graph slicing), DARPA TRACTOR / C2Rust (transpile-then-refactor), and Syzygy (dual code-and-test verification)—converges on the six-step workflow in Figure 6. Follow it left to right:
-
Stage 0 — Slice dependencies and clean inputs (
AlphaTranspattern).
Purpose: Map program call graphs and copybook dependencies bottom-up, and strip legacy*comment banners before sending files to an AI.
Why: Real mainframes connect hundreds of programs across CICS, JCL, and DB2. Slicing lets you migrate one module at a time, and stripping comment banners cuts bloated token bills immediately. -
Stage 1 — Build a fast throwaway copy (
GPT-6.1 Sol, 13 minutes).
Purpose: Generate a mechanical, runnable Java build whose only job is matching legacy math to the exact cent when live mainframe runs are blocked.
Why: Mechanical transpiling is fast and captures odd edge cases when live COBOL is unavailable. Treat it strictly as a fallback proxy, never as ground truth. -
Freeze a large test baseline (
Freeze Baseline).
Purpose: Run 10,000 or more boundary, synthetic, and historical claims and lock every input and output pair as your reference baseline.
Why: Most teams start with a few dozen test cases that miss rare branches. Freezing 10,000 pairs gives Stage 2 a fast, automated safety net.
Massive caveat with Stage 1: an AI-built throwaway copy is not ground truth. If GPT-6.1 Sol misreads a rare COBOL branch, rounding rule, or mainframe sort order, freezing 10,000 outputs from Stage 1 alone will lock that bug into Stage 2. Whenever live COBOL, a compiled test runner, or historical batch logs exist, generate your frozen baseline from real COBOL instead of Stage 1. Use Stage 1 as a proxy baseline only when mainframe execution is blocked, and cross-check it against real batch outputs plus human review of edge cases before freezing.
-
Extract and sign off on business rules (
Rule Spec— Human Sign-Off).
Purpose: Produce a plain-English list of extracted business rules and let domain owners approve ambiguous edge cases before Stage 2 starts.
Why: Automated tests cannot decide whether production should keep mainframe EBCDIC sort rules (like'14A'through'149') or Linux behavior. Signing off on the spec upfront prevents silent policy bugs. -
Stage 2 — Co-generate clean Java and rule tests (
Gemini 4 Neon, 23 minutes;Syzygypattern).
Purpose: Refactor the logic into small Java classes, load rate tables from external files, and write one executable JUnit test per signed-off business rule.
Why: Writing code and tests together guarantees every policy area is proven to auditors instead of leaving rules untested. -
Run the automated verification loop (
Verify→Java 17).
Purpose: Check every edit against all 10,000 frozen outputs, a 10% external rate-file change, and the full JUnit rule suite, repairing any failure automatically.
Why: Catching a 1-cent diff or broken rate override immediately prevents billing errors. OnOPPS, Stages 1 and 2 finished in about 36 minutes total.
This workflow mirrors DARPA's TRACTOR program and C2Rust to C2SaferRust pipelines, which lock behavior before refactoring. Our results add a twist: agents now build that Stage 1 transpiler themselves in 13 minutes. For large estates wired with CICS, JCL, and DB2, Stage 0 call-graph slicing keeps each migration step small and safe.
| Technique | Representative Model | Exact Match | Blind Score | PMD-CPD | Relative Cost | Best Role |
|---|---|---|---|---|---|---|
| Single-Shot | Gemini 4 Argon (1/6 passed) | 60/60 | 5.67 | 4.5% | Low | Small programs (<7K LOC) only. |
| Custom Transpiler | GPT-6.1 Sol (port.py) |
60/60 | 5.00 | 73.7% | Lowest | Stage 1 fallback proxy synthesis. |
| Parameterized Engine | Opus 5.5 / Argon | 60/60 | 6.33–6.67 | 4.0–35.7% | Moderate–Highest | Middle ground; leaves big engine classes. |
| Modular Refactor | Gemini 4 Neon | 60/60 | 9.00 | 3.3% | Moderate | Stage 2 maintainable production Java. |
| Multi-Stage Hybrid | Sol → Neon (anchored baseline) | 100% locked | 9.00 | <4% | Moderate | Recommended production workflow (see Section 3). |
Verifying Without Legacy Tests or SMEs
When legacy tests and subject-matter experts are scarce, teams still need to trace every diff to one COBOL rule. Our differential harness checks nine claim fields and seven line fields per record, so a failing field points to one pricing section. Because Stage 1 keeps original COBOL paragraph names as Java methods like p20000ProcessMainNew and p20100Init, engineers can trace state side by side against Stage 2.
Every mismatch falls into one of three buckets:
- Java conversion defects. Fix bugs in Stage 2 and re-run the differential check until every field matches to
$0.00. - COBOL compiler precision flags. Audit baseline compiler flags, such as GnuCOBOL
-farithmetic-osvs, whenever intermediate math drifts. - Platform and runtime ambiguities. Send platform differences, such as EBCDIC versus ASCII sort order for codes
'14A'through'149', to a domain owner for written sign-off and a permanent unit test.
We evaluated Stage 1 (GPT-6.1 Sol) and Stage 2 (Gemini 4 Neon) separately against compiled GnuCOBOL rather than in one automated chain.
Migration factory vs. generic coding agents: A generic coding agent stops when the code compiles and a few happy-path checks pass. A migration factory enforces repeatable offline gates inside your own environment. Those gates check field-level exact-cent diffs, +10% external rate overrides, duplication and coverage ceilings, and human sign-off on runtime ambiguities.
Four Mainframe Traps That Require Human Sign-Off
Automated tests cannot decide whether your new Java should keep mainframe quirks or match Linux behavior. Before you trust any migration pipeline, watch out for four traps we hit directly:
- Open-source COBOL compilers can quietly corrupt your test baseline. GnuCOBOL truncates math at 18 digits under its IBM flag, zeroing all 63
OPPSclaims. Add-fno-arithmetic-osvsand audit compiler math flags before trusting any test outputs. - Mainframes and Linux sort letters and digits in opposite orders. A billing rule covering
'14A'through'149'caused our only mismatch across 119 unseen claims.NeonandArgonkept mainframe intent while four models matched Linux, proving domain owners must choose. - COBOL record moves can silently shift decimal places. Copying raw text directly into a numeric field turned a
$203deductible into$300. Always wrap incoming text slices in fixed-width record structures before numeric moves. - AI agents will hunt for blocked compilers during evaluations.
Claude Opus 5.5searched disk folders for COBOL tools and tried to download GnuCOBOL from the web. Lock evaluation containers offline with strict root permissions so tests measure real code conversion.
Bottom Line
AI agents now make exact COBOL translation cheap enough that token bills no longer block modernization. To ship Java your team can own next year, run a two-stage workflow and verify rate overrides. Watch for bloated tokenizers, and keep your own architects on final sign-off.
Study Limits
We ran each model once per program across the full benchmark. An earlier 45-minute timeout stopped Gemini 4 Carbon right after it deleted its test file.
Public reference code disclosure: CMS began publishing Java reference source JARs on CMS.gov in Q1 2021, so models may have seen Medicare OPPS code in training. Three forensic checks show the models still translated OPPSCAL.cob directly. First, Sol and Sonnet 5.5 wrote Python COBOL parsers (port.py, cobparse.py) that generated 1,024 paragraph methods. Second, all seven passing builds formatted our custom 72 + 46×N fixed-width output layout and kept COBOL WORKING-STORAGE structure. Third, three of seven builds (Neon, Opus 5.5, and single-shot Argon) parsed raw copybooks at runtime. That let them pass all 60 unseen +10% rate claims, where 50 of the 60 outputs changed.
Scope boundary: This study tested standalone batch COBOL programs up to 41,918 lines, not multi-million-line estates wired across CICS, JCL, DB2, SQL stored procedures, and .NET services. Mixed enterprise estates also require Stage 0 call-graph slicing, stored-procedure extraction, and cross-service integration tests. You can inspect all 24 run logs, blind reviews, and Docker scripts in the Appendix.