Java Reference · java.lang
Java String.toUpperCase() and toLowerCase() methods
Reference for Java String.toUpperCase() and toLowerCase(): convert case, why the Locale matters (Turkish i, German sharp s), and safe comparison.
toUpperCase() and toLowerCase() return a new string with every character converted to upper or lower case. The original string is unchanged. Both exist in two forms: one that uses the JVM's default Locale, and one that takes a Locale explicitly.
The locale is the part that bites people. Case rules are language-specific, so the same code can give different results on a machine configured for Turkish. When the text is a protocol keyword, a file extension or an identifier rather than human language, pass Locale.ROOT.
String a = "Java".toUpperCase(Locale.ROOT); // "JAVA" String b = "Java".toLowerCase(Locale.ROOT); // "java"
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input · what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input · what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public String toUpperCase() public String toUpperCase(Locale locale) public String toLowerCase() public String toLowerCase(Locale locale)
| Name | Description |
|---|---|
locale |
The rules to apply. Locale.ROOT means language-neutral rules. |
Returns: the converted string. If nothing changes, the same String object is returned.
Throws: NullPointerException if locale is null.
Usage notes
- The no-argument forms use
Locale.getDefault(). Under a Turkish, Azeri or Lithuanian default,"TITLE".toLowerCase()produces a dotlessı, and"i".toUpperCase()yieldsİ. That breaks comparisons with ASCII keywords. - Length can change. The German
ßbecomesSSin upper case, so the result may be longer than the input. Never assumetoUpperCase()keeps the index positions. - Not always reversible. Upper-casing and then lower-casing may not return the original text.
- Use
equalsIgnoreCase()for comparison. It does not allocate, and it is the standard way to compare ignoring case. For locale-sensitive text comparison, usejava.text.Collator. - Normalize map keys with
toLowerCase(Locale.ROOT)so case-insensitive lookups are stable across machines, or use aTreeMapwithString.CASE_INSENSITIVE_ORDER. - Characters:
Character.toUpperCase(char)handles a single character and cannot expandß. - Cost: O(n); a fast path avoids allocation when the string is already in the target case.