What is the method for converting strings in Java between upper and lower case?
6 Answers
String#toLowerCase and String#toUpperCase are the methods you need.
-
Although 'toUpperCase' will give the opposite effect, I'll still give you +1 :-)– FortegaDec 23, 2009 at 10:11
-
Fixed (including linking to Java6 docs - does anyone even still use 1.4?) and upvoted. Dec 23, 2009 at 10:38
-
1@Fortega - the OP said "converting between" not "converting from / to". Converting between implies converting in both directions. Dec 23, 2009 at 12:29
There are methods in the String class; toUppercase()
and toLowerCase()
.
i.e.
String input = "Cricket!";
String upper = input.toUpperCase(); //stores "CRICKET!"
String lower = input.toLowerCase(); //stores "cricket!"
This will clarify your doubt
Yes. There are methods on the String itself for this.
Note that the result depends on the Locale the JVM is using. Beware, locales is an art in itself.
-
Yup. I recently discovered that the size of string is not always the same as the size of string.toUpperCase()– FortegaDec 23, 2009 at 10:19
-
Yes but only in those weird languages with umlauts and Eszett and names like Thorbjørn :-) Dec 23, 2009 at 10:33
-
2
-
4Actually we use ISØ-Låtin-1 here in Sĉändïñävïä so it could be a LØT WØRSË :) Dec 23, 2009 at 11:55
Assuming that all characters are alphabetic, you can do this:
From lowercase to uppercase:
// Uppercase letters.
class UpperCase {
public static void main(String args[]) {
char ch;
for(int i=0; i < 10; i++) {
ch = (char) ('a' + i);
System.out.print(ch);
// This statement turns off the 6th bit.
ch = (char) ((int) ch & 65503); // ch is now uppercase
System.out.print(ch + " ");
}
}
}
From uppercase to lowercase:
// Lowercase letters.
class LowerCase {
public static void main(String args[]) {
char ch;
for(int i=0; i < 10; i++) {
ch = (char) ('A' + i);
System.out.print(ch);
ch = (char) ((int) ch | 32); // ch is now uppercase
System.out.print(ch + " ");
}
}
}
Coverting the first letter of word capital
input:
hello world
String A = hello;
String B = world;
System.out.println(A.toUpperCase().charAt(0)+A.substring(1) + " " + B.toUpperCase().charAt(0)+B.substring(1));
Output:
Hello World