Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Capitalize the First Letter of a String in Java Using Regex
Next article icon

Java Program to Capitalize the First Letter of Each Word in a String

Last Updated : 07 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java Programming, we can be able to capitalize the first letter of each word in the given String value by using toUpperCase(), toLowerCase(), and another one is substring() method. These methods are available String class in Java and these methods are useful for our problem.

In this article, we will learn how to capitalize the first letter of each word in a String in Java using different methods.

Approach to capitalize the first letter of each word in a String

To capitalize the first letter of each word in a String, first, we have taken one String value then take the first character from each word in the given string then print the result.

  • First, we have created one Java class.
  • After that, we created one method that is capitalizeWords() which capitalizes the first letter of each word in a String
  • After that, we called this method in the main method and then gave input to the method already taken String value.
  • Finally, print the result.

Program to capitalize the first letter of each word in a String in Java

1. Using split() and substring() methods

Below is the implementation of split() and substring() methods to capitalize the first letter of each word in a String.

Java
// Java Program to capitalize the first letter of each word in a String using split() and substring() methods import java.util.Arrays; public class CapitalizeWordsExample {     public static void main(String[] args) {         // input string         String input = "welcome to geeksforgeeks";          // call the capitalizeWords function and store the result         String result = capitalizeWords(input);          // print the original and modified strings         System.out.println("Input: " + input);         System.out.println("Output: " + result);     }      // function to capitalize the first letter of each word     public static String capitalizeWords(String input) {         // split the input string into an array of words         String[] words = input.split("\\s");          // StringBuilder to store the result         StringBuilder result = new StringBuilder();          // iterate through each word         for (String word : words) {             // capitalize the first letter, append the rest of the word, and add a space             result.append(Character.toTitleCase(word.charAt(0)))                   .append(word.substring(1))                   .append(" ");         }          // convert StringBuilder to String and trim leading/trailing spaces         return result.toString().trim();     } } 

Output
Input welcome to geeksforgeeks  Output Welcome To Geeksforgeeks      

Explanation of the Program:

  • In the above program, we have taken one input string value that is welcome to geeksforgeeks.
  • After this we split this String into String array by using split() method.
  • After that we have taken each character from word by using loop from string array.
  • Then change that character from small to capital.
  • Then Append the Result to String builder after that it will print the result.

2. Using Java Streams

Java
// Java Program to capitalize the first letter of each word in a String using Java Streams import java.util.Arrays; import java.util.stream.Collectors;  public class CapitalizeWordsExample {     public static void main(String[] args) {         // input string         String input = "welcome to geeksforgeeks";          // call the capitalizeWords function and store the result         String result = capitalizeWords(input);          // print the original and modified strings         System.out.println("Input: " + input);         System.out.println("Output: " + result);     }      // function to capitalize the first letter of each word using Java streams     public static String capitalizeWords(String input) {         // split the input string into an array of words, stream the array         // apply the capitalization transformation and join the words back         return Arrays.stream(input.split("\\s"))                      .map(word -> Character.toTitleCase(word.charAt(0)) + word.substring(1))                      .collect(Collectors.joining(" "));     } } 

Output
Input: welcome to geeksforgeeks  Output: Welcome To Geeksforgeeks      

Explanation of the Program:

  • In the above program, first we have taken a String Value as input.
  • After that converted it into streams by using Array class.
  • Then take the first letter from the word and change into Capital letter then added to the collection.
  • Finally print the result.

3. Using StringBuilder

In this Java code, we have taken one string value, after that we have taken first letter of each word and converted it into capitalize then print the result.

Java
// Java Program to capitalize the first letter of each word in a String using StringBuilder import java.util.Arrays; public class CapitalizeWordsExample  {     public static String capitalizeWords(String input)      {         if (input == null || input.isEmpty())          {             return input;         }          // split the input string into words using whitespace         String[] words = input.split("\\s");          // create a StringBuilder         StringBuilder result = new StringBuilder();          for (String word : words)          {             // capitalize the first letter of each word and append the rest of the word             result.append(Character.toUpperCase(word.charAt(0)))                   .append(word.substring(1).toLowerCase())                   .append(" "); // Add a space between words         }          // remove the trailing space and return the capitalized string         return result.toString().trim();     }      public static void main(String[] args)      {              String inputString = "welcome to geeksforgeeks";         String capitalizedString = capitalizeWords(inputString);          System.out.println("Original String: " + inputString);         System.out.println("Capitalized String: " + capitalizedString);     } } 

Output
Original String: welcome to geeksforgeeks  Capitalized String: Welcome To Geeksforgeeks      

Explanation of the Program:

  • In this above example, first we have taken one string value in main method.
  • After that we have used capitalizeWords().
  • To this method, we have given String value as input.
  • This method can be able to convert capitalize the first letter of each word in a String by using this function.
  • In this user defined function first, we have checked the given string is empty or not, if given String is empty this function returns the empty value as a string.
  • After that we have converted the String into String array by using split method.
  • After that we have created the StringBuilder class object.

Next Article
Capitalize the First Letter of a String in Java Using Regex

E

eswararaobetha1
Improve
Article Tags :
  • Java
  • Java Programs
  • Java-String-Programs
  • strings
  • Java Examples
Practice Tags :
  • Java
  • Strings

Similar Reads

  • Capitalize the First Letter of a String in Java
    In Java, to check if a String contains only uppercase letters, we can use many approaches. These approaches verify each character in the String to ensure they are all in uppercase. A simple method, such as iterating through the characters and checking their case. In this article, we will discuss how
    4 min read
  • Capitalize the First Letter of a String in Java Using Regex
    In Java, we can use regular expressions to make the first character of each word in Uppercase as the word is represented as a String and string is the collection of characters. So, in Java, we can use pattern and matcher class methods to find the first character of a word and then replace it with it
    2 min read
  • Capitalize the first and last character of each word in a string
    Given the string, the task is to capitalise the first and last character of each word in a string.Examples: Input: Geeks for geeks Output: GeekS FoR GeekS Input: Geeksforgeeks is best Output: GeeksforgeekS IS BesT Approach Create a character array of the StringRun a loop from the first letter to the
    6 min read
  • Java program to swap first and last characters of words in a sentence
    Write a Java Program to Swap first and last character of words in a Sentence as mentioned in the example? Examples: Input : geeks for geeks Output :seekg rof seekg Approach:As mentioned in the example we have to replace first and last character of word and keep rest of the alphabets as it is. First
    2 min read
  • Java Program to find the Last Index of a Particular Word in a String
    To find out the last occurrence of a character or string from a given string across which the substring or character is been searched over and returning the index value of the character or substring is found. Real-life Example: Consider an example of a book. The book contains pages where pages conta
    4 min read
  • Java program to count the characters in each word in a given sentence
    Write a Java program to count the characters in each word in a given sentence? Examples: Input : geeks for geeksOutput :geeks->5for->3geeks->5 Recommended: Please solve it on PRACTICE first, before moving on to the solution. Approach:Here we have to find out number of words in a sentence an
    3 min read
  • How to find the first and last character of a string in Java
    Given a string str, the task is to print the first and the last character of the string. Examples: Input: str = "GeeksForGeeks" Output: First: G Last: s Explanation: The first character of the given string is 'G' and the last character of given string is 's'. Input: str = "Java" Output: First: J Las
    3 min read
  • Java Program to Remove a Given Word From a String
    Given a string and a word that task to remove the word from the string if it exists otherwise return -1 as an output. For more clarity go through the illustration given below as follows. Illustration: Input : This is the Geeks For Geeks word="the" Output : This is Geeks For Geeks Input : Hello world
    3 min read
  • Java Program to Swap Corner Words and Reverse Middle Characters of a String
    Given a string containing n numbers of words. The task is to swap the corner words of the string and reverses all the middle characters of the string. Input: "Hello this is the GFG user" Output: "user GFG eth si siht Hello" Input: "Hello Bye" Output: "Bye Hello" Methods: Using the concept of ASCII v
    5 min read
  • Java Program to Replace Multiple Characters in a String
    In this program, we will be discussing various methods for replacing multiple characters in String. This can be done using the methods listed below: Using String.replace() methodUsing replaceAll() method Using replaceFirst() method Method 1: Using String.replace() method This method returns a new st
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences