Modern Java in LaTeX listings (Java 17)

If you use the LaTeX listings package to typeset Java, you’ve probably noticed that modern Java has moved faster than the package itself. Records, var, and text blocks may not highlight correctly out of the box. The good news: the listings package is extensible so that you can teach it “modern Java” with a tiny language definition.

The minimal language extension for Java 17

Here’s a drop‑in snippet that builds on the stock Java lexer to support key Java 17 features:

What each line does:

  • language = Java: inherit all of the listings’ built‑in Java rules.
  • morekeywords = {var,record}: colorize var and record as keywords (var is contextual, but highlighting it improves readability in code listings).
  • deletekeywords = {label}: avoid mistakenly highlighting labeled statements like label: for (…) { … }. label is not a Java keyword; removing it prevents false positives.
  • morestring=[b]”””: treat triple quotes as a balanced string delimiter so Java text blocks highlight as a single string.

Using it in your document

Activate the language globally:

…or per listing:

If you already have a custom style (e.g., mystyle) with colors and fonts, combine them:

Minimal working example

This is a compact MWE you can compile with pdflatex, xelatex, or lualatex. Adjust the style to your taste:

Here’s the result, where you can see the differences (note in the standard behavior the wrong highlighting of the double-quoted string in the text-block):

Happy highlighting! 🙂

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.