- Capitalize the first letter of a string in Java
- You might also like.
- Capitalize the first letter of each word in a string using Java
- You might also like.
- How to capitalize first letter in java
- Further reading:
- Was this post helpful?
- Share this
- Related Posts
- Author
- Related Posts
- Count occurrences of Character in String
- Find first and last digit of a number
- Happy Number program in Java
- Find Perfect Number in Java
- How to find Magic Number in Java
- Number guessing game in java
Capitalize the first letter of a string in Java
In this quick tutorial, you will learn how to capitalize the first letter of a string in Java. Unfortunately, the String class does not provide any method to capitalize strings. However, there are methods available to change the case of the string (uppercase, lowercase, etc.).
The simplest way to capitalize the first letter of a string in Java is by using the String.substring() method:
String str = "hello world!"; // capitalize first letter String output = str.substring(0, 1).toUpperCase() + str.substring(1); // print the string System.out.println(output); // Hello world!
The above example transforms the first letter of string str to uppercase and leaves the rest of the string the same. If the string is null or empty, the above code throws an exception. However, we can write a functional capitalize() that makes sure the string has at least one character before using the substring() method:
public static String capitalize(String str) if(str == null || str.isEmpty()) return str; > return str.substring(0, 1).toUpperCase() + str.substring(1); >
Now just call the capitalize() method whenever you want to make the first letter of a string uppercase:
System.out.println(capitalize("hello world!")); // Hello world! System.out.println(capitalize("heLLo")); // HeLLo System.out.println(capitalize(null)); // null
Notice the 2nd line of the above code snippet, only the first letter is capitalized. If you want to ensure only the first letter is in uppercase and the remaining string is lowered case, you can do the following:
str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase()
The Apache Commons Lang library is another way to capitalize the first letter of a string in Java. If you are using Gradle, add the following dependency to your build.gradle file:
implementation 'org.apache.commons:commons-lang3:3.9'
dependency> groupId>org.apache.commonsgroupId> artifactId>commons-lang3artifactId> version>3.9version> dependency>
The StringUtils class from Commons Lang provides the capitalize() method to change the first letter to uppercase:
System.out.println(StringUtils.capitalize("apache commons")); // Apache commons System.out.println(StringUtils.capitalize("heLLO")); // HeLLO System.out.println(StringUtils.uncapitalize(null)); // null
Apache Commons Lang offers many extra methods that are not included in standard Java libraries ( java.lang package). It includes String manipulation methods, basic numerical methods, object reflection, concurrency, creation and serialization, and System properties.
In this article, we looked at different ways to capitalize the first letter of a string in Java. The simple approach is to use the String class’s substring() method. However, if you are already using Apache Commons Lang in your project, just use the StringUtils class to capitalize the first letter of a string. Since string capitalization is a common task in all programming languages, I have also written a tutorial to do the same in JavaScript. Take a look at this guide. Read Next: Capitalize the first letter of each word in a string using Java ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.
You might also like.
Capitalize the first letter of each word in a string using Java
In this short guide, you will learn how to capitalize the first letter of each word in a string using Java. We have already learned to capitalize the first letter of a string in Java. But capitalizing each word in a string is a bit tricky.
The easiest way to capitalize the first character of each word of a string is by using Java 8 Stream API:
String str = "welcome to java"; // uppercase first letter of each word String output = Arrays.stream(str.split("\\s+")) .map(t -> t.substring(0, 1).toUpperCase() + t.substring(1)) .collect(Collectors.joining(" ")); // print the string System.out.println(output); // Welcome To Java
In the above example, we first split the string into an array using the split() method. The array is passed to Arrays.stream() as a parameter that turns it into a Stream object. Afterward, we use the map() method from streams to capitalize each word before converting it back to a string using the collect() method. If the string is empty or null , the above code will throw an exception. Let us write a function capitalizeAll() that makes sure there is no exception while transforming string:
public static String capitalizeAll(String str) if (str == null || str.isEmpty()) return str; > return Arrays.stream(str.split("\\s+")) .map(t -> t.substring(0, 1).toUpperCase() + t.substring(1)) .collect(Collectors.joining(" ")); >
System.out.println(capitalizeAll("welcome to java")); // Welcome To Java System.out.println(capitalizeAll("this is awesome")); // This Is Awesome System.out.println(capitalizeAll("mcdonald in lahore")); // Mcdonald In Lahore System.out.println(capitalizeAll(null)); // null
The above solution only changes the first letter of each word while all other characters remain the same. Sometimes, you want to ensure that only the first character of a word is capitalized. Let us write another function capitalizeFully() for this:
public static String capitalizeFully(String str) if (str == null || str.isEmpty()) return str; > return Arrays.stream(str.split("\\s+")) .map(t -> t.substring(0, 1).toUpperCase() + t.substring(1).toLowerCase()) .collect(Collectors.joining(" ")); >
The only difference between capitalizeAll() and capitalizeFully() is that the latter function explicitly changes the remaining part of the word to lowercase:
System.out.println(capitalizeFully("i aM aTTa")); // I Am Atta System.out.println(capitalizeFully("fOo bAr")); // Foo Bar
If you are using Java 9 or higher, it is possible to use a regular expression with the String.replaceAll() method to capitalize the first letter of each word in a string. The String.replaceAll() method replaces each substring of this string that matches the given regular expression with the given replacement. Here is an example:
public static String capitalizeAll(String str) if (str == null || str.isEmpty()) return str; > return Pattern.compile("\\b(.)(.*?)\\b") .matcher(str) .replaceAll(match -> match.group(1).toUpperCase() + match.group(2)); >
System.out.println(capitalizeAll("12 ways to learn java")); // 12 Ways To Learn Java System.out.println(capitalizeAll("i am atta")); // I Am Atta System.out.println(capitalizeAll(null)); // null
The Apache Commons Text library is yet another option to convert the first character of each word in a string to uppercase. Add the following dependency to your build.gradle file:
implementation 'org.apache.commons:commons-text:1.8'
dependency> groupId>org.apache.commonsgroupId> artifactId>commons-textartifactId> version>1.8version> dependency>
Now you can use the capitalize() method from the WordUtils class to capitalize each word in a string:
System.out.println(WordUtils.capitalize("love is everywhere")); // Love Is Everywhere System.out.println(WordUtils.capitalize("sky, sky, blue sky!")); // Sky, Sky, Blue Sky! System.out.println(WordUtils.capitalize(null)); // null
The good thing about WordUtils methods is that they handle the exceptions gracefully. There won’t be any exception even if the input is null . The WordUtils class also provides the capitalizeFully() method that capitalizes the first character and turns the remaining characters of each word into lowercase:
System.out.println(WordUtils.capitalizeFully("fOO bAR")); // Foo Bar System.out.println(WordUtils.capitalizeFully("sKy is BLUE!")); // Sky Is Blue!
You might also like.
How to capitalize first letter in java
Here are the steps to capitalize first letter of each word.
- Split String by space and assign it String array words
- Iterate over the String array words and do following:
- Get first letter of String firstLetter using str.substring(0,1) .
- Get remaining String remainingLetters using str.substring(1) .
- Convert first letter of String firstLetter to upper Case using toUpperCase() method.
- Concatenate both the String firstLetter and remainingLetters .
That’s all about How to capitalize first letter in java.
Further reading:
Count occurrences of Character in String in Java
Count number of words in a String
Was this post helpful?
Share this
Related Posts
Author
Related Posts
Count occurrences of Character in String
Table of Contents1. Using String Library Methods2. Using Recursion3. Using Hashing ConceptUsing ArraysUsing Collections (Map)4. Using Java 8 Features In this article, we will look at a problem: Given an Input String and a Character, we have to Count Occurrences Of character in String. For Example, If the Given String is : «Java2Blog» and we […]
Find first and last digit of a number
Table of ContentsAlgorithmUsing while loopUsing log() and pow() methodsUsing while loop and pow() method In this article, we are going to find first and last digit of a number. To find first and last digit of any number, we can have several ways like using modulo operator or pow() and log() methods of Math class […]
Happy Number program in Java
Table of ContentsWhat is a Happy Number?Using HashsetAlgorithmExampleUsing slow and fast pointersAlgorithmExample In this article, we are going to learn to find Happy Number using Java. Let’s first understand, what is Happy Number? What is a Happy Number? A number which leaves 1 as a result after a sequence of steps and in each step […]
Find Perfect Number in Java
Table of ContentsIterative approachRecursive approach In this article, we are going to find whether a number is perfect or not using Java. A number is called a perfect number if the sum of its divisors is equal to the number. The sum of divisors excludes the number. There may be several approaches to find the […]
How to find Magic Number in Java
Table of ContentsWhat is a Magic Number?Algorithm for Magic NumberExample to find Magic NumberAnother Example To find Magic Number In this article, we are going to learn to find Magic Number using Java. Let’s first understand, what is Magic Number? What is a Magic Number? A number which leaves 1 as a result after a […]
Number guessing game in java
Table of ContentsNumber guessing game RulesAlgorithm for Number guessing game In this article, we will implement Number guessing game in java. The number guessing game is based on a concept where player guesses a number between a range. If player guesses the exact number then player wins else player looses the game. Since this game […]