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.
The toUpperCase( ) method converts all the characters in a string to uppercase.
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:
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:
Uppercase String (Turkish Locale): HELLO WORLD!
Java String toUpperCase() method – Interview Questions
Q 1: What does toUpperCase() method do?
Q 2: Does it modify the original string?
Q 3: Is toUpperCase() locale-dependent?
Q 4: What is the return type?
Q 5: Can toUpperCase() convert numbers?
Java String toUpperCase() method – Objective Questions (MCQs)
Q1. What does the toUpperCase() method do?
Q2. What will "java".toUpperCase() return?
Q3. The toUpperCase() method returns a new string because strings in Java are:
Q4. What happens when toUpperCase() is called on a null string?
Q5. Which class defines the toUpperCase() method?