Changing the case of a string
Java's String class has two methods for changing letter case. toUpperCase() turns every letter into its capital form, and toLowerCase() turns every letter into its small form. Characters that aren't letters, such as digits, spaces and punctuation, pass through unchanged.
String word = "Hello World";
String upper = word.toUpperCase(); // "HELLO WORLD"
String lower = word.toLowerCase(); // "hello world"
String name = "ALICE";
System.out.println(name.toLowerCase()); // alice
System.out.println("ABC123!".toLowerCase()); // abc123!
Both methods take no arguments, and the parentheses are required. Without them, word.toUpperCase is not a valid expression in Java.
The original string does not change
Strings in Java are immutable: once created, their characters can't be modified. The case methods therefore build and return a new string, and the variable you called them on keeps its old value:
String word = "Hello World";
System.out.println(word.toUpperCase()); // HELLO WORLD
System.out.println(word); // Hello World
If you want to keep the converted text, store it in a variable. Calling word.toUpperCase(); on a line by itself computes a result and then discards it.
Why case conversion is useful
The main use is comparing text without caring about capitalization. The method equals is case-sensitive, so "Hello".equals("hello") is false. Converting both sides to the same case makes the check fair:
String a = "Hello";
String b = "hELLO";
System.out.println(a.equals(b)); // false
System.out.println(a.toLowerCase().equals(b.toLowerCase())); // true
System.out.println(a.equalsIgnoreCase(b)); // true
For a plain comparison, equalsIgnoreCase is shorter and doesn't build any new strings. Case conversion shines when you need the converted text itself, for example to normalize user input before storing it, or to build a search that ignores case, such as text.toLowerCase().indexOf(word.toLowerCase()).
Combining the methods
Because every call returns a string, you can build bigger operations from small ones. Capitalizing only the first letter of a word takes two slices of the string and a case method:
String w = "java";
String cap = w.substring(0, 1).toUpperCase() + w.substring(1);
System.out.println(cap); // Java
w.substring(0, 1) is the first character as a string, w.substring(1) is everything after it, and + joins the converted first letter back onto the rest. A case-insensitive search works the same way:
String text = "Learning JAVA is fun";
System.out.println(text.indexOf("java")); // -1
System.out.println(text.toLowerCase().indexOf("java")); // 9
The plain search fails because JAVA in capitals does not match java. Lowercasing the text first lets it match at index 9. Index 9 is also valid for the original text, since case conversion keeps the length the same for ordinary English letters.
The lesson's exercise
The starting code has one variable:
String word = "Hello World";
The task is to create an uppercase and a lowercase version, in two steps:
- Declare a
Stringnamedupperand assign itword.toUpperCase(). It holds"HELLO WORLD". - Declare a
Stringnamedlowerand assign itword.toLowerCase(). It holds"hello world".
Both variables are computed from word, which keeps its original capitalization the whole time. The complete code is:
String word = "Hello World";
String upper = word.toUpperCase();
String lower = word.toLowerCase();
Gotchas
- Use the return value. The methods don't modify
word. Writingword.toUpperCase();without assigning does nothing useful. - The result can be longer. Some letters expand when capitalized. In German,
"straße".toUpperCase()gives"STRASSE", one character longer than the input. - The default locale can matter. The no-argument versions use the computer's language settings. For a few languages, Turkish being the well-known case, the letter
iconverts differently. When the text is a code or a keyword rather than human language, pass a locale to be safe:s.toLowerCase(Locale.ROOT), which needsimport java.util.Locale;. - Empty strings are fine.
"".toUpperCase()returns an empty string, and no exception is thrown. Anullreference does throw aNullPointerException, as with any method call onnull. - Single characters have their own methods. For a
char, useCharacter.toUpperCase(c)andCharacter.toLowerCase(c). - Case conversion doesn't capitalize just the first letter. There is no built-in method for that. Combine
substringwith the case methods when you need it.
Key takeaways
toUpperCase()andtoLowerCase()return a new string with every letter converted.- Strings are immutable, so assign the result to a variable to keep it.
- Convert both sides to the same case, or use
equalsIgnoreCase, to compare text regardless of capitalization.