|
How to capitalize a word
The following example shows capitalizing the first character of given string.
|
package com.bethecoder.articles.basics.capitalize;
public class CapitalizeWordTest {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(captalize(null));
System.out.println(captalize(""));
System.out.println(captalize("java"));
System.out.println(captalize("hello world"));
System.out.println(captalize("be the coder"));
System.out.println(captalize("ABCD"));
}
public static String captalize(String str) {
if (str == null || str.trim().length() == 0) {
return str;
}
return Character.toUpperCase(str.charAt(0)) +
(str.length() > 1 ? str.substring(1) : "");
}
}
|
| |
It gives the following output,
null
Java
Hello world
Be the coder
ABCD
|
|