String Capitalize Java

Java comes with toUpperCase() and toLowerCase() methods that converts all the characters of the string into uppercase or lowercase. String Capitalize example keeps all String characters in capital letters.

Following are the method signatures.

  1. String toLowerCase(): Converts all the characters of the string into lowercase. Returns a string with all lowercase letters. Remember, the original string is not disturbed (string is immutable).
  2. String toUpperCase(): Converts all the characters of the string into uppercase. Returns a string with all uppercase letters. Original string is not disturbed. Still the programmer can use the original string with original format.
The following program on String Capitalize uses the above two methods.
public class StringUpperLower
  public static void main(String args[])
  {                                     // TO CAPITALIZE FULL STRING
    String str1 = "hello Sir";
    System.out.println("Original string str1: " + str1);
    String str2 = str1.toUpperCase();
    System.out.println("str1 changed to all uppercase: " + str2);// TO CAPITALIZE FIRST CHARACTER ONLY AND REMAINING LOWERCASE
    String str3 = str1.substring(0, 1).toUpperCase() + str1.substring(1).toLowerCase();
    System.out.println("str1 changed only first character to uppercase: " + str3);
		                        // TO CONVERT INTO LOWERCASE
    String str4 = "GOOD MORNING";
    System.out.println("\nOriginal string str4: " + str4);
    String str5 = str4.toLowerCase();
    System.out.println("str4 changed all characters to lowercase: " + str5);

String Capitalize
Output screen on String Capitalize Java

String str1 = “hello Sir”;
String str2 = str1.toUpperCase();

toUpperCase() method of String class converts the all the characters of the string str1 into uppercase. The returned string str2 contains all uppercase letters. Observe the screenshot.

String str3 = str1.substring(0, 1).toUpperCase() + str1.substring(1).toLowerCase();

The toUpperCase() method can be used in combination with substring() to convert a few characters of the string.

str1.substring(0, 1) method returns a string containing only the first character and the substring(1) returns a string containing from 1st to the last character of the string str1.

String str4 = “GOOD MORNING”;
String str5 = str4.toLowerCase();

str4.toLowerCase() method converts all the string str4 characters into lowercase. The method returns str5 with all the lowercase letters. Still, str4 is untouched and in original format only. Similar methods also exist with C/C++.

Java split() method is illustrated in Region Matches – Interning – Splitting and JDK 1.4 (J2SE 4) Version.

1 thought on “String Capitalize Java”

Leave a Comment

Your email address will not be published.