Convert Camel Case to Snake Case in Java
When working with text transformations in Java, you may often need to convert between different naming conventions, such as Camel Case and Snake Case. These formats are widely used in programming and understanding how to transition between them can be highly beneficial. This article will guide you through the process of converting Camel Case to Snake Case in Java, explaining different methods to achieve this.
1. Understanding Camel Case and Snake Case
- Camel Case: In Camel Case, words are concatenated without spaces, and each word (except the first) begins with a capital letter.
- Example:
camelCaseExample
,myVariableName
.
- Example:
- Snake Case: In Snake Case, words are separated by underscores (
_
), and all letters are typically lowercase.- Example:
snake_case_example
,my_variable_name
.
- Example:
1.1 Key Differences
- Camel Case is standard in Java for variable and method names, whereas Snake Case is often used in database schemas or configuration files.
- Camel Case relies on capitalization to separate words, while Snake Case uses underscores.
2. Using Regular Expressions
The most efficient way to convert Camel Case to Snake Case is by using regular expressions, which allows us to match patterns in text and replace them systematically.
public class RegexCamelToSnakeConverter { private static final Logger logger = Logger.getLogger(RegexCamelToSnakeConverter.class.getName()); public static String convertToSnakeCase(String camelCase) { // Replace lowercase-uppercase patterns with an underscore between them return camelCase.replaceAll("([a-z])([A-Z])", "$1_$2") .replaceAll("([A-Z])(?=[A-Z])", "$1_") .toLowerCase(); } public static void main(String[] args) { String camelCase = "camelCaseExample"; String snakeCase = convertToSnakeCase(camelCase); logger.log(Level.INFO, "Snake Case: {0}", snakeCase); } }
In the above code snippet, the replaceAll
method identifies patterns where a lowercase letter is immediately followed by an uppercase letter, and $1_$2
inserts an underscore between the matched groups. The toLowerCase
method ensures that the resulting output is entirely in lowercase. The resulting output from the code sample is:
Jan 28, 2025 10:22:41 P.M. com.jcg.examples.RegexCamelToSnakeConverter main INFO: Snake Case: camel_case_example
3. Using a Manual Loop
If regular expressions feel overkill or you want more control, a manual approach using a StringBuilder
can also be effective.
public class LoopCamelToSnakeConverter { private static final Logger logger = Logger.getLogger(LoopCamelToSnakeConverter.class.getName()); public static String convertToSnakeCase(String camelCase) { StringBuilder result = new StringBuilder(); for (char c : camelCase.toCharArray()) { // If the character is uppercase, add an underscore before converting to lowercase if (Character.isUpperCase(c)) { result.append("_").append(Character.toLowerCase(c)); } else { result.append(c); } } return result.toString(); } public static void main(String[] args) { String camelCase = "camelCaseExample"; String snakeCase = convertToSnakeCase(camelCase); logger.log(Level.INFO, "Snake Case: {0}", snakeCase); } }
This approach utilizes a StringBuilder
to construct the Snake Case string. For each character, if it is uppercase, an underscore is added before appending its lowercase equivalent. This method provides greater control, making it ideal for handling edge cases or applying additional formatting requirements.
Output is the same as the previous example:
4. Conclusion
Converting Camel Case to Snake Case is a common task when working with various programming conventions. The regular expression approach is concise and efficient, while the manual loop provides greater control. Choosing the right approach depends on your specific use case, project size, and preference for code readability or control.
5. Download the Source Code
This article focused on the conversion between Java camel case and snake case.
You can download the full source code of this example here: Java camel snake case conversion