In this Blog, we will learn how the camel case works in Java with a clear and understandable example. In Java, camel case is nothing but a Naming Convention . I know you are thinking about what is naming convention is, it is a set of rules used to name variables, methods, etc.
Some rules to follow
- The starting word starts with lowercase letter.
- The next word starts with an uppercase letter.
- It doesn’t allow spaces, dashes (-), or underscores ( _ )
Example
welcome to-code_speedy -> welcomeToCodeSpeedy
Here in this example, I changed the first word’s starting letter to lowercase, then I changed every first letter to uppercase after a special character.
Code
String[] splitIntoWords = input.split("[\\s-_]+");
Here we are using the inbuilt split method in Java to split the String into words separated by special characters.
\\s: this is for whitespaces.
-: This is for hyphen.
_: This is for underscore.
+: This means it matches one or more of the characters.
StringBuilder result = new StringBuilder(words[0].toLowerCase());
Here, the meaning of this code snippet is converting the first word’s first letter to lowercase using the StringBuilder class in Java.
for(int i = 1; i<splitIntoWords.length;i++) { String word= splitIntoWords[i]; if (word.length()>0) { camelCase.append(Character.toUpperCase(word.charAt(0))); camelCase.append(word.substring(1).toLowerCase()); } }
In this code, there are some operations performed. I’ll explain it line by line.
- The first line is a loop for converting the words into camel case.
- The second line is taking each word from the array.
- The third line is a conditional statement it checks whether the word length is greater than zero or not.
- Then the next line is performing operations the toUpperCase() method used to convert a single character into uppercase. for camel case, we need to convert every starting letter of the word except the first word.
- The final line converts the remaining letters into lowercase using a method toLowerCase() method. method
- The final step is to append to the string.
Advantages:
- Easy to read.
- Easy to Understand.
- Easy to maintain.
- More consistent for team projects.