Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Overview

Camel and snake cases are two common naming conventions often used in programming. While the camel case utilizes capital letters to signify the start of a new word (camelCaseExample), the snake case separates words using underscores (snake_case_example).

In this tutorial, we’ll explore how to implement such a conversion in Java.

2. Understanding the Conversion

When converting a camel case string into a snake case one, we need to:

  • Identify boundaries between words
  • Insert an underscore (`_`) at each boundary
  • Make sure all letters are lowercase

For example:

  • Input: “convertCamelCase”
  • Output: “convert_camel_case”

With this in mind, let’s examine ways to achieve this transformation.

3. Using a Manual Approach

To begin with, the simplest approach involves iterating over the characters in a string and adding underscores when encountering uppercase letters:

public static String convertCamelCaseToSnake(String input) {
    StringBuilder result = new StringBuilder();
    for (char c : input.toCharArray()) {
        if (Character.isUpperCase(c)) {
            result.append("_").append(Character.toLowerCase(c));
        } else {
            result.append(c);
        }
    }
    return result.toString();
}

Let’s now break down what we’re doing in this method:

  • Iterate through each character in the string
  • When an uppercase letter is encountered, prepend an underscore and convert it to lowercase
  • For all other characters, directly append them

Finally, let’s test our implementation:

@Test
public void whenConvertNormalCamelCase_thenGetCorrectSnakeCase() {
    String input = "convertCamelCase";
    String expected = "convert_camel_case";
    Assertions.assertEquals(expected, CamelToSnakeCaseConverter.convertCamelCaseToSnake(input));
}

@Test
public void whenConvertNotNormalCamelCase_thenGetCorrectSnakeCase() {
    String input = "convertCCamelCase";
    String expected = "convert_c_camel_case";
    Assertions.assertEquals(expected, CamelToSnakeCaseConverter.convertCamelCaseToSnake(input));
}

@Test
public void whenConvertAlreadySnakeCase_thenGetUnchangedSnakeCase() {
    String input = "snake_case";
    String expected = "snake_case";
    Assertions.assertEquals(expected, CamelToSnakeCaseConverter.convertCamelCaseToSnake(input));
}

@Test
public void whenConvertAllLowerCaseString_thenGetUnchangedString() {
    String input = "snakecase";
    String expected = "snakecase";
    Assertions.assertEquals(expected, CamelToSnakeCaseConverter.convertCamelCaseToSnake(input));
}

@Test
public void whenConvertOtherEdgeCases_thenGetCorrectSnakeCases() {
    // Blank string
    Assertions.assertEquals("", CamelToSnakeCaseConverter.convertCamelCaseToSnake(""));

    // Special character
    String input = "sn@keCase#";
    String expected = "sn@ke_case#";
    Assertions.assertEquals(expected, CamelToSnakeCaseConverter.convertCamelCaseToSnake(input));
}

4. Using Regular Expressions

Alternatively, regular expressions simplify the task by defining patterns for uppercase letters and replacing them:

public static String convertCamelCaseToSnakeRegex(String input) {
    return input
      .replaceAll("([A-Z])(?=[A-Z])", "$1_")
      .replaceAll("([a-z])([A-Z])", "$1_$2")
      .toLowerCase();
}

Here’s how it works:

  • The replaceAll(“([A-Z])(?=[A-Z])”, “$1_”) method adds an underscore between adjacent uppercase letters.
  • The replaceAll(“([a-z])([A-Z])”, “$1_$2”) method adds an underscore before uppercase letters that follow lowercase letters.
  • Finally, the entire result is converted to lowercase.

Let’s also verify this method:

@Test
public void whenConvertNormalCamelCase_thenGetCorrectSnakeCase() {
    String input = "convertCamelCase";
    String expected = "convert_camel_case";
    Assertions.assertEquals(expected, CamelToSnakeCaseConverter.convertCamelCaseToSnakeRegex(input));
}

@Test
public void whenConvertNotNormalCamelCase_thenGetCorrectSnakeCase() {
    String input = "convertCCamelCase";
    String expected = "convert_c_camel_case";
    Assertions.assertEquals(expected, CamelToSnakeCaseConverter.convertCamelCaseToSnakeRegex(input));
}

@Test
public void whenConvertAlreadySnakeCase_thenGetUnchangedSnakeCase() {
    String input = "snake_case";
    String expected = "snake_case";
    Assertions.assertEquals(expected, CamelToSnakeCaseConverter.convertCamelCaseToSnakeRegex(input));
}

@Test
public void whenConvertAllLowerCaseString_thenGetUnchangedString() {
    String input = "snakecase";
    String expected = "snakecase";
    Assertions.assertEquals(expected, CamelToSnakeCaseConverter.convertCamelCaseToSnakeRegex(input));
}

@Test
public void whenConvertOtherEdgeCases_thenGetCorrectSnakeCases() {
    // Blank string
    Assertions.assertEquals("", CamelToSnakeCaseConverter.convertCamelCaseToSnakeRegex(""));

    // Special character
    String input = "sn@keCase#";
    String expected = "sn@ke_case#";
    Assertions.assertEquals(expected, CamelToSnakeCaseConverter.convertCamelCaseToSnakeRegex(input));
}

5. Handling Edge Cases

When converting camel case strings to snake case, it’s essential to handle various edge cases, such as:

  • Empty strings: ensure our function returns an empty string
  • All lowercase strings: input should remain unaffected
  • Strings already in snake case: ensure the function doesn’t change such strings
  • Special characters: they should remain unaffected

6. Conclusion

In conclusion, we explored two approaches to converting camel case to snake case in Java: the manual approach using iteration and the more concise method leveraging regular expressions.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW