The toUpperCase() method in Java is used to convert all characters in a string to uppercase. This method returns a new string where all alphabetic characters are converted to their uppercase form, while other characters (non-alphabetic) remain unchanged.
Syntax:
str.toUpperCase() // where str is a string value
Note: Converts all characters of the string to uppercase based on the default locale.
When we use locale for this method.
str.toUpperCase(locale) // where str is a string value
Note: Converts all characters to uppercase based on the rules of the specified Locale. This is particularly useful for non-English languages where uppercase conversion rules might differ.
Important Points
- The method does not modify the original string; it returns a new string with the characters converted to uppercase.
- The method does not affect non-alphabetic characters (like numbers, spaces, or punctuation).
- The toUpperCase() method is locale-sensitive, meaning that it can respect regional differences in uppercase conversion if you use the version that accepts a Locale.
Example:
public class StringUpperCaseExample {
public static void main(String[] args) {
String str = "Hello, World!";
// Convert string to uppercase
String upperStr = str.toUpperCase();
System.out.println("Original String: " + str); // Output: Hello, World!
System.out.println("Uppercase String: " + upperStr); // Output: HELLO, WORLD!
}
}
Output:
Original String: Hello, World!
Uppercase String: HELLO, WORLD!
Uppercase String: HELLO, WORLD!
Using toUpperCase(Locale locale)
import java.util.Locale;
public class ToUpperCaseExample {
public static void main(String[] args) {
String str = "hello world!";
// Convert string to uppercase using a specific Locale (e.g., turkish)
String upperStr = str.toUpperCase(Locale.forLanguageTag("tr"));
System.out.println("Original String: " + str); // Output: hello world!
System.out.println("Uppercase String (Turkish Locale): " + upperStr); // Output: HELLO WORLD!
}
}
Output:
Original String: hello world!
Uppercase String (Turkish Locale): HELLO WORLD!
Uppercase String (Turkish Locale): HELLO WORLD!