English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented Programming(I)

Java Object-Oriented Programming(II)

Java Object-Oriented Programming(III)

Java Exception Handling

Java List

Java Queue(Queue)

Java Map Collection

Java Set Collection

Java Input Output(I/O)

Java Reader/Writer

Other Java Topics

Java program capitalizes the first character of each word in the string

Java Examples Comprehensive

In this example, we will learn how to capitalize the first letter of a string in Java.

Example1:Java program to capitalize the first letter of String

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.

Example2:Convert each word in the string 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

Java Examples Comprehensive