English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this example, we will learn how to capitalize the first letter of a string in Java.
class Main { public static void main(String[] args) { //Create a string String name = "w3codebox"; //Create two substrings from name //The first substring contains the first letter of name //The second substring contains the remaining letters String firstLetter = name.substring(0, 1); String remainingLetters = name.substring(1, name.length()); //Change the first letter to uppercase firstLetter = firstLetter.toUpperCase(); //Concatenate two substrings name = firstLetter + remainingLetters; System.out.println("Name: ", + name); } }
Output Result
Name: w3codebox
In this example, we will convert the first letter of the string name to uppercase.
class Main { public static void main(String[] args) { //Create a string String message = "everyone loves java"; //Store each character in a char array char[] charArray = message.toCharArray(); boolean foundSpace = true; for(int i = 0; i < charArray.length;++) { //If the array element is a letter if(Character.isLetter(charArray[i])) { // Check if there is a space before the letter if(foundSpace) { //Change this letter to uppercase charArray[i] = Character.toUpperCase(charArray[i]); foundSpace = false; } } else { //If the new character is not a character foundSpace = true; } } //Convert the character array to a string message = String.valueOf(charArray); System.out.println("Message: " + message); } }
Output Result
Message: Everyone Loves Java
Here,
We create a string named message
We convert the string to a char array
We access each element of the char array
If the element is a space, we will convert the next element to uppercase