⬅ Previous Topic
Java StringtoString()
methodNext Topic ⮕
Java Stringtrim()
methodtoUpperCase()
method⬅ Previous Topic
Java StringtoString()
methodNext Topic ⮕
Java Stringtrim()
methodThe toUpperCase()
method in Java is a handy tool for converting a string to uppercase. It's particularly useful when you need to standardize input or ensure consistency across different parts of your program. Let’s dive into how it works and explore some examples.
public String toUpperCase()
public String toUpperCase(Locale locale)
Parameter | Description |
---|---|
locale |
Optional. A Locale object that defines the rules for uppercase conversion based on a specific language or region. If omitted, the default locale of your system is used. |
The toUpperCase()
method returns a new string representing the uppercase version of the original string. The original string remains unchanged.
This example demonstrates how to convert a simple string to uppercase using the default locale.
String str = "hello world";
String upperCaseStr = str.toUpperCase();
System.out.println(upperCaseStr);
HELLO WORLD
Explanation: The original string "hello world" is converted to uppercase, resulting in the new string “HELLO WORLD”, which is then printed to the console.
This example shows how to use a specific locale (Turkish) for uppercase conversion. Turkish has different rules for some characters compared to English.
import java.util.Locale;
String str = "merhaba dünya";
String upperCaseStr = str.toUpperCase(Locale.forLanguageTag("tr-TR"));
System.out.println(upperCaseStr);
MERHABA DÜNYA
Explanation: The string "merhaba dünya" is converted to uppercase using the Turkish locale (tr-TR). This ensures that any characters specific to Turkish are handled correctly during the conversion process. Note that in some locales, certain characters may not be uppercased.
This example demonstrates how the method handles strings containing special characters and numbers.
String str = "Java123!@#";
String upperCaseStr = str.toUpperCase();
System.out.println(upperCaseStr);
JAVA123!@#
Explanation: The special characters and numbers remain unchanged as toUpperCase()
only affects alphabetic characters.
This example illustrates the behavior when passing a null string to the method. It's important to handle null values gracefully in your code.
String str = null;
String upperCaseStr = (str != null) ? str.toUpperCase() : ""; //Handle NullPointerException
System.out.println(upperCaseStr);
Explanation: Attempting to call toUpperCase()
directly on a null string would result in a NullPointerException. To avoid this, we check if the string is not null before calling the method. If it's null, we assign an empty string as the default value.
⬅ Previous Topic
Java StringtoString()
methodNext Topic ⮕
Java Stringtrim()
methodYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.