← Back to DevBytes

IntelliJ IDEA Code Snippets: Complete Guide

What Are IntelliJ IDEA Code Snippets (Live Templates)?

IntelliJ IDEA code snippets, officially called Live Templates, are predefined or custom code fragments that expand automatically when you type a short abbreviation and press Tab (or the configured expansion key). Think of them as intelligent boilerplate generators that insert commonly used code patterns, complete with dynamic placeholders, variable references, and context-aware transformations — all in a single keystroke.

Unlike static text expansions found in simpler editors, IntelliJ's Live Templates are deeply integrated with the IDE's code intelligence. They understand the surrounding context, infer types, suggest variable names, and can even prompt you with expression choices at expansion time. This makes them vastly more powerful than copy-paste or plain snippet tools.

Why Live Templates Matter

🚀 Deploy your AI agent in 10 minutes

Managed Hermes hosting. Zero DevOps. 100M tokens/mo included.

Try it free →

Every developer writes repetitive code: getters and setters, loops, try-catch blocks, test method stubs, logging statements, and framework-specific boilerplate. Manually typing these patterns costs time, introduces typos, and breaks flow. Live Templates address all three problems:

Built-In Live Templates

IntelliJ IDEA ships with dozens of ready-to-use templates organized by scope. Here are the most essential ones every Java developer should know:

Java Core Templates

Main method:

// Abbreviation: psvm
// Expansion:
public static void main(String[] args) {
    $END$
}

For-each loop:

// Abbreviation: iter
// Expansion:
for (String $VAR$ : $ITERABLE$) {
    $END$
}

For-i loop:

// Abbreviation: fori
// Expansion:
for (int $INDEX$ = 0; $INDEX$ < $LIMIT$; $INDEX$++) {
    $END$
}

If statement:

// Abbreviation: ifn (if null)
// Expansion:
if ($VAR$ == null) {
    $END$
}

Try-catch:

// Abbreviation: tryc
// Expansion:
try {
    $CODE$
} catch ($EXCEPTION$ $CATCH_VAR$) {
    $END$
}

Logging Templates

Log statement with SLF4J/Log4j:

// Abbreviation: logr (log error)
// Expansion:
LOGGER.error("$MESSAGE$", $THROWABLE$);

Testing Templates (JUnit)

Test method:

// Abbreviation: test
// Expansion:
@Test
public void $METHOD_NAME$() {
    // given
    $GIVEN$

    // when
    $WHEN$

    // then
    $THEN$
    $END$
}

How to Use Live Templates

Using a built-in template is straightforward:

  1. Place the cursor where you want the code to appear.
  2. Type the abbreviation (e.g., psvm, iter, sout).
  3. Press Tab (or Ctrl+J / Cmd+J if Tab is remapped).
  4. If the template contains variables, the first one is highlighted. Type its value or accept the suggestion.
  5. Press Tab or Enter to move to the next variable; press Shift+Tab to move back.
  6. Press Esc or finish editing to exit the template session and land at $END$.

You can also invoke the full list via Ctrl+J (Cmd+J on macOS), which displays a popup of all templates available in the current context:

// Press Ctrl+J (Cmd+J) anywhere in a Java file
// A popup appears listing all available templates
// Start typing to filter, then press Enter on the desired one

Creating Custom Live Templates

The real power comes from creating your own templates tailored to your project's patterns. Here's the complete step-by-step process:

Step 1: Open the Settings

Navigate to File → Settings → Editor → Live Templates (on macOS: IntelliJ IDEA → Preferences → Editor → Live Templates).

Step 2: Choose or Create a Template Group

Templates are organized into groups (like "Java", "Kotlin", "Groovy"). You can add your templates to existing groups or create a new group for your project-specific snippets. Click the + button and select Template Group..., then name it (e.g., "MyProject").

Step 3: Add a New Live Template

Select your group, click + again, and choose Live Template. Fill in:

Step 4: Set the Applicable Context

Click Define (or Change) at the bottom and select the language/file types where this template should be available. For Java templates, check Java → Declaration, Expression, Statement etc. You must select at least one context, or the template will never appear.

Practical Example: Custom Builder Pattern Template

Let's create a template for a common builder pattern setter method:

// Template abbreviation: bldr
// Template text:
public $CLASS_NAME$ $SETTER_NAME$($TYPE$ $PARAM$) {
    this.$FIELD$ = $PARAM$;
    return this;
    $END$
}

After defining this, typing bldr + Tab in a class body expands to a complete builder setter with return, and lets you tab through CLASS_NAME, SETTER_NAME, TYPE, PARAM, and FIELD.

Template Variables and Expression Functions

Variables are the heart of Live Templates. They appear as $VARIABLE_NAME$ in the template text. When the template expands, variables become interactive placeholders. You can define their behavior in the Edit Template Variables dialog (click the "Edit variables" button in the template editor).

Built-in Expression Functions

Each variable can have an expression function that determines its default value. Here are the most powerful ones:

// snippet() — Reuse another template's expansion
$METHOD_BODY$   expression: snippet("methodBody")

// className() — Returns the enclosing class name
$CLASS$   expression: className()

// methodName() — Returns the enclosing method name
$METHOD$   expression: methodName()

// variableOfType("type") — Suggests variables matching the type
$LIST$   expression: variableOfType("java.util.List")

// suggestVariableName() — Infers a good variable name
$VAR$   expression: suggestVariableName()

// groovyScript("...") — Execute custom Groovy logic
$CONVERTED$   expression: groovyScript("_1.toLowerCase()", VARIABLE)

Practical Example: Logger Declaration Template

This template automatically inserts the correct class name into the logger declaration:

// Abbreviation: logc (log class)
// Template text:
private static final Logger LOGGER = LoggerFactory.getLogger($CLASS$.class);
// Variable definition:
// $CLASS$ → expression: className()

When you type logc + Tab inside any class, it expands to:

private static final Logger LOGGER = LoggerFactory.getLogger(MyActualClass.class);

No typing required — className() resolves the enclosing class automatically.

Advanced: Groovy Script Expressions

For complex transformations, use groovyScript() to run arbitrary Groovy code:

// Template: Generate a constant from a string
// Abbreviation: const
// Template text:
public static final String $CONST_NAME$ = "$VALUE$";
// Variables:
// $VALUE$   → default: "input value"
// $CONST_NAME$ → expression: groovyScript("_1.replaceAll(' ', '_').toUpperCase()", VALUE)

If you enter "max retry count" for $VALUE$, $CONST_NAME$ becomes MAX_RETRY_COUNT.

Postfix Completion — Templates in Reverse

IntelliJ also offers Postfix Completion, which works like Live Templates but applied after you've typed an expression. Type a dot followed by the postfix keyword and press Tab. For example:

// Type:  list.for
// Press Tab, expands to:
for (Object item : list) {

}

// Type:  name.nn
// Press Tab, expands to:
if (name != null) {

}

// Type:  value.var
// Press Tab, expands to:
Type value = value;  // with inferred type

Postfix completions are configured alongside Live Templates in Settings → Editor → General → Postfix Completion. You can enable/disable individual postfixes and see the full list. Common ones include .if, .else, .null, .nn, .for, .fori, .while, .sout, .var, .cast, and .try.

Sharing Templates with Your Team

Live Templates are stored in the IDE configuration and can be shared in several ways:

Export Example Command Line

You can also export templates non-interactively using the IDE's command-line tools:

# Export all live templates to an XML file
idea.exe dumpSharedSettings --output=templates.xml --setting=live_templates

# Import on another machine
idea.exe applySharedSettings --input=templates.xml

Best Practices for Live Templates

1. Keep Abbreviations Short and Mnemonic

Use 3–5 character abbreviations that hint at the expansion. psvm (public static void main) is memorable because it uses first letters. bldr for builder, logc for logger class — pick conventions and stick to them.

2. Use Scopes Precisely

Only assign templates to contexts where they make sense. A JPA repository template should be limited to Java → Declaration, not available inside method bodies. Precise scoping prevents clutter in the completion popup and accidental expansions.

3. Leverage Expression Functions Over Manual Typing

Whenever possible, use className(), methodName(), variableOfType(), and suggestVariableName() rather than leaving variables as plain editable text. This reduces keystrokes and eliminates mistakes.

4. Set Meaningful Default Values

For variables without expression functions, set sensible defaults in the "Default value" column. For example, in a loop template, default $LIMIT$ to 10 or array.length. Users can override, but a good default means the template often works with just Tab presses.

5. Nest Templates with snippet()

The snippet() expression function lets you compose larger templates from smaller building blocks. Define atomic templates (like a single field declaration) and combine them into larger patterns (like a full builder class skeleton) without duplicating code.

6. Review and Prune Regularly

Templates accumulate over time. Periodically review your list — remove ones you no longer use, update outdated patterns, and ensure abbreviations don't conflict. A bloated template list makes the Ctrl+J popup harder to navigate.

7. Document Custom Templates for the Team

Maintain a simple README or wiki page listing team-specific templates with their abbreviations, expansions, and intended use cases. This onboarding step prevents the "secret productivity features" problem where only senior devs know about the shortcuts.

8. Test Templates in Isolation

When creating complex templates with Groovy scripts or multiple snippet() calls, test them in a scratch file (File → New → Scratch File) before adding to your production template set. Verify the expansion works in all expected contexts.

Surround Templates

IntelliJ also offers Surround Templates — a related feature where you select existing code and wrap it with a template. Access these via Ctrl+Alt+T (Cmd+Opt+T on macOS) or Code → Surround With. Built-in surrounds include:

// Select a block of code, press Ctrl+Alt+T, choose:
// Surround with try-catch
// Surround with if/while/for
// Surround with synchronized
// Surround with Runnable/Callable

You can create custom surround templates in the same Live Templates settings by selecting Surround Template instead of Live Template when adding. The template text uses $SELECTION$ as the placeholder for the wrapped code.

// Custom surround template example
// Abbreviation: lock
// Template text:
synchronized ($LOCK$) {
    $SELECTION$
}
// After selecting code and pressing Ctrl+Alt+T, choose 'lock'
// The selected code gets wrapped in a synchronized block

Troubleshooting Common Issues

Template Doesn't Expand

Variables Not Being Replaced

Groovy Script Not Working

Conclusion

IntelliJ IDEA's Live Templates system transforms repetitive coding from a manual chore into an automated, keystroke-efficient workflow. By mastering built-in templates, creating project-specific custom ones, and leveraging expression functions like className() and groovyScript(), you eliminate boilerplate typing, reduce errors, and maintain consistent code patterns across your codebase. The combination of Live Templates, Postfix Completion, and Surround Templates gives you a complete toolkit for code generation that adapts to your specific frameworks and conventions. Start by learning the built-in abbreviations, then gradually build your own template library — the time invested pays for itself within days of consistent use.

🚀 Need a reliable AI agent for your project?

Deploy Hermes Agent in 10 minutes. Managed hosting, zero DevOps.

Get Started — $23.99/mo
← Back to all articles