The String
type provides two methods for converting strings between upper case and lower case:
toUpperCase
to convert all characters to upper casetoLowerCase
to convert all characters to lower caseThese methods both return the converted strings as new String
instances: the original String
objects are not modified because String
is immutable in Java. See this for more on immutability : Immutability of Strings in Java
String string = "This is a Random String";
String upper = string.toUpperCase();
String lower = string.toLowerCase();
System.out.println(string); // prints "This is a Random String"
System.out.println(lower); // prints "this is a random string"
System.out.println(upper); // prints "THIS IS A RANDOM STRING"
Non-alphabetic characters, such as digits and punctuation marks, are unaffected by these methods. Note that these methods may also incorrectly deal with certain Unicode characters under certain conditions.
Note: These methods are locale-sensitive, and may produce unexpected results if used on strings that are intended to be interpreted independent of the locale. Examples are programming language identifiers, protocol keys, and HTML
tags.
For instance, "TITLE".toLowerCase()
in a Turkish locale returns "tıtle
", where ı (\u0131)
is the LATIN SMALL LETTER DOTLESS I character. To obtain correct results for locale insensitive strings, pass Locale.ROOT
as a parameter to the corresponding case converting method (e.g. toLowerCase(Locale.ROOT)
or toUpperCase(Locale.ROOT)
).
Although using Locale.ENGLISH
is also correct for most cases, the language invariant way is Locale.ROOT
.
A detailed list of Unicode characters that require special casing can be found on the Unicode Consortium website.
Changing case of a specific character within an ASCII string:
To change the case of a specific character of an ASCII string following algorithm can be used:
Steps:
Voila, the Case of the character is changed.
An example of the code for the algorithm is:
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the String");
String s = scanner.next();
char[] a = s.toCharArray();
System.out.println("Enter the character you are looking for");
System.out.println(s);
String c = scanner.next();
char d = c.charAt(0);
for (int i = 0; i <= s.length(); i++) {
if (a[i] == d) {
if (d >= 'a' && d <= 'z') {
d -= 32;
} else if (d >= 'A' && d <= 'Z') {
d += 32;
}
a[i] = d;
break;
}
}
s = String.valueOf(a);
System.out.println(s);