toUpperCase(), toLowerCase() and replace() String

toUpperCase(), toLowerCase() and replace() String


Here, we do some miscellaneous operations on strings like converting a string from lowercase to uppercase or vice versa, removing unwanted prefix and suffix whitespaces and replacing a few characters with replace() String.

Supported methods from String class.

  1. String toLowerCase(): Returns a new string containing all lowercase characters. All the uppercase characters are converted into lowercase. But the original string is not affected (remember, strings are immutable).
  2. String toUpperCase(): Returns a new string containing all uppercase characters. All the lowercase characters are converted into uppercase. But the original string is not disturbed.
  3. String replace(char ch1, char ch2): Replaces all the occurrences of character ch1 with character ch2. Returns a new string, but the original string is intact.
  4. String replace(String str1, String str2): Replaces all the occurrences of string str1 with string str2. Returns a new string, but the original string is undisturbed.
The above methods usage is illustrated in the following program including replace() String.

replace() String

replace() String etc.

String s3 = s1.toUpperCase();

All the lowercase characters of s1 are converted to uppercase and with the new values, a new string s3 is created and returned. Remember, the original string is not disturbed with the methods toUpperCase(), toLowerCase() and replace() as strings are designed to be immutable.

String s5 = s4.trim();

The prefix and suffix whitespace of s4 is deleted. After deletion, a new string s5 is created and returned.

String s7 = s6.replace('r','R');

All the r characters of s6 are replaced with R and a new string s7 is created and returned.

String s9 = s8.replace("BB","bbb");

All the "BB" characters of s8 are replaced with "bbb" and a new string s9 is created and returned. Two characters are replaced by three characters.

2 thoughts on “toUpperCase(), toLowerCase() and replace() String

  1. test

    Hi, Neat publish. There is a problem with your site in internet explorer, would go here… IE nonetheless will be the marketplace chief and also a large a part of people may omit your current great writing due to this problem.

Leave a Reply

Your email address will not be published. Required fields are marked *