Computer >> Computer tutorials >  >> Programming >> Java

Java Program to Capitalize the first character of each word in a String


In this article, we will understand how to capitalize the first character of each word in a string. String is a datatype that contains one or more characters and is enclosed in double quotes(“ ”).

Below is a demonstration of the same −

Suppose our input is

Input string: java program

The desired output would be

The string after capitalizing the first letter is: Java program

Algorithm

Step 1 - START
Step 2 - Declare three strings namely input_string, first_letter, remaining_letters.
Step 3 - Define the values.
Step 4 - Get the first word of the string into a sub-string and use the function . toUpperCase() to convert the substring to uppercase. Concat the sub-string with the string.
Step 5 - Display the result
Step 6 - Stop

Example 1

Here, we bind all the operations together under the ‘main’ function.

public class Capitalize {
   public static void main(String[] args) {
      String input_string = "java program";
      System.out.println("The string is defined as: " +input_string);
      String first_letter = input_string.substring(0, 1);
      String remaining_letters = input_string.substring(1, input_string.length());
      first_letter = first_letter.toUpperCase();
      input_string = first_letter + remaining_letters;
      System.out.println("The string after capitalizing the first letter is: " + input_string);
   }
}

Output

The string is defined as: java program
The string after capitalizing the first letter is: Java program

Example 2

Here, we encapsulate the operations into functions exhibiting object oriented programming.

public class Capitalize {
   public static String capitalize_letter(String input_string){
      String first_letter = input_string.substring(0, 1);
      String remaining_letters = input_string.substring(1, input_string.length());
      first_letter = first_letter.toUpperCase();
      input_string = first_letter + remaining_letters;
      return input_string;
   }
   public static void main(String[] args) {
      String input_string = "java program";
      System.out.println("The string is defined as: " +input_string);
      String result = capitalize_letter(input_string);
      System.out.println("The string after capitalizing the first letter is: " + result);
   }
}

Output

The string is defined as: java program
The string after capitalizing the first letter is: Java program