How to Capitalize String in Java Program

Capitalize String in Java

This example program about, How to Capitalize String in Java.

Capitalize String in Java without using Library

CapitalizeExample1.java

package com.dineshkrish.commons;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class CapitalizeExample1 {

	public static String doCapitalize(String strValue) {

		// Defining StringBuilder Object
		StringBuilder sb = new StringBuilder();

		if (strValue != null && !strValue.isEmpty()) {

			// Splitting the String 
			String[] words = strValue.split(" ");

			for (int i = 0; i < words.length; i++) {

				// Capitalizing String using 'replaseFirst()' method
				words[i] = words[i].replaceFirst(String.valueOf(words[i]
						.charAt(0)), String.valueOf(Character
						.toUpperCase(words[i].charAt(0))));
				
				// Appending String to StringBuilder
				sb.append(words[i] + " ");
			}
		}

		return sb.toString();
	}

	public static void main(String[] args) {

		String changed = doCapitalize("dinesh krishnan");

		System.out.println(changed);
	}
	
}
Output
Dinesh Krishnan

Capitalize String in Java using Apache Commons Library

commons-lang3-3.5.jar

Download Here

CapitalizeExample2.java

package com.dineshkrish.commons;

import org.apache.commons.lang3.text.WordUtils;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class CapitalizeExample2 {

	public static void main(String[] args) {
		
		// Actual String Value
		String strValue = "dinesh krishnan";
		
		// Calling the method from Apache Commons API
		String capitalized = WordUtils.capitalize(strValue);
		
		
		// Printing the Result
		System.out.println("Before Capitalize :"+strValue);
		
		System.out.println("Afer Captialize :"+capitalized);
	}
	
}
Output
Before Capitalize :dinesh krishnan
Afer Captialize :Dinesh Krishnan

References

1. Apache Commons API
2. Apache Commons WordUtil API
3. Java String replaceFirst() method

Hello everyone, I am a Founder of dineshkrish.com.