In this post, we will how to capitalize first letter in java
Capitalize first letter of String
Here are the steps to convert first letter of string to uppercase in java
- Get first letter of String
firstLetStr
usingstr.substring(0,1)
. - Get remaining String
remLetStr
usingstr.substring(1)
. - Convert first letter of String
firstLetStr
to upper Case usingtoUpperCase()
method. - Concatenate both the String
firstLetStr
andremLetStr
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package org.arpit.java2blog; public class CapitalizeFirstLetterMain { public static void main(String[] args) { // create a string String name = "java2blog"; System.out.println("Original String: " + name); // get First letter of the string String firstLetStr = name.substring(0, 1); // Get remaining letter using substring String remLetStr = name.substring(1); // convert the first letter of String to uppercase firstLetStr = firstLetStr.toUpperCase(); // concantenate the first letter and remaining string String firstLetterCapitalizedName = firstLetStr + remLetStr; System.out.println("String with first letter as Capital: " + firstLetterCapitalizedName); } } |
Output:
Original String: java2blog
String with first letter as Capital: Java2blog
String with first letter as Capital: Java2blog
Capitalize first letter of each word
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
usingstr.substring(0,1)
. - Get remaining String
remainingLetters
usingstr.substring(1)
. - Convert first letter of String
firstLetter
to upper Case usingtoUpperCase()
method. - Concatenate both the String
firstLetter
andremainingLetters
.
- Get first letter of String
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package org.arpit.java2blog; public class CapitalizeFirstLetterMain { public static void main(String[] args) { // create a string String str = "this is java code"; String words[]=str.split("\\s"); String capitalizeStr=""; for(String word:words){ // Capitalize first letter String firstLetter=word.substring(0,1); // Get remaining letter String remainingLetters=word.substring(1); capitalizeStr+=firstLetter.toUpperCase()+remainingLetters+" "; } System.out.println(capitalizeStr); } } |
Output:
This Is Java Code
That’s all about How to capitalize first letter in java.
Further reading:
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.