Convert Between camelCase And snake_case (Java)

Convert identifiers between camelCase and snake_case: insert underscores before capitals in one direction, capitalize after them in the other.

JavaData Integrity

Code

snippet
public class CaseConverter {

    // camelCase -> snake_case:在大写字母前插入下划线再整体小写
    static String toSnake(String camel) {
        return camel
                .replaceAll("([a-z0-9])([A-Z])", "$1_$2")
                .toLowerCase();
    }

    // snake_case -> camelCase:下划线后的首字母转大写
    static String toCamel(String snake) {
        StringBuilder out = new StringBuilder(snake.length());
        boolean upper = false;
        for (char c : snake.toCharArray()) {
            if (c == '_') {
                upper = true;
            } else if (upper) {
                out.append(Character.toUpperCase(c));
                upper = false;
            } else {
                out.append(c);
            }
        }
        return out.toString();
    }

    public static void main(String[] args) {
        System.out.println(toSnake("createdAtUtc"));
        System.out.println(toSnake("orderItemId"));
        System.out.println(toCamel("created_at_utc"));
        System.out.println(toCamel("user_id_2_token"));
    }
}

How it works

Convert Between camelCase And snake_case (Java) comes down to the class CaseConverter and the functions toSnake, toCamel and main.

The cycling part of this snippet is for (char c : snake.toCharArray()).

Points of care

  • Runs with what the toolchain already gives you — nothing extra.

Putting it to use

The primary signature is static String toSnake(String camel)

The entry point wires toSnake and toCamel together — run it once and the whole demo flows.

Core lines

return out.toString();

Interactive Tools for This Topic

FAQ

How do you run Convert Between camelCase And snake_case (Java)?
Run it as a complete program — compile or interpret the file directly; there is nothing to install first.