Java How to Convert String to Uppercase Easily
In Java, you can convert a string to uppercase by using the
toUpperCase() method like this: String upper = original.toUpperCase();.Examples
Inputhello
OutputHELLO
InputJava Programming
OutputJAVA PROGRAMMING
Input123abc!
Output123ABC!
How to Think About It
To convert a string to uppercase, think of changing every letter to its capital form. Java provides a built-in method
toUpperCase() that does this for you by scanning each character and converting it if it is a lowercase letter.Algorithm
1
Get the input string.2
Call the <code>toUpperCase()</code> method on the string.3
Store or return the new uppercase string.Code
java
public class Main { public static void main(String[] args) { String original = "hello world"; String upper = original.toUpperCase(); System.out.println(upper); } }
Output
HELLO WORLD
Dry Run
Let's trace the string "hello world" through the code
1
Original string
original = "hello world"
2
Convert to uppercase
upper = original.toUpperCase() -> "HELLO WORLD"
3
Print result
Output: HELLO WORLD
| Step | String Value |
|---|---|
| Initial | hello world |
| After toUpperCase() | HELLO WORLD |
Why This Works
Step 1: Using toUpperCase()
The toUpperCase() method creates a new string where all lowercase letters are changed to uppercase.
Step 2: Immutable strings
Strings in Java cannot be changed, so toUpperCase() returns a new string instead of modifying the original.
Step 3: Printing the result
The new uppercase string is printed to show the conversion result.
Alternative Approaches
Using Locale with toUpperCase()
java
import java.util.Locale; public class Main { public static void main(String[] args) { String original = "hello world"; String upper = original.toUpperCase(Locale.ENGLISH); System.out.println(upper); } }
This approach is useful to handle locale-specific uppercase rules, ensuring consistent results across different languages.
Complexity: O(n) time, O(n) space
Time Complexity
The method processes each character once, so the time grows linearly with the string length.
Space Complexity
A new string is created to hold the uppercase result, so space also grows linearly with input size.
Which Approach is Fastest?
Using toUpperCase() with or without locale has similar performance; locale-aware calls add slight overhead but improve correctness.
| Approach | Time | Space | Best For |
|---|---|---|---|
| toUpperCase() | O(n) | O(n) | Simple uppercase conversion |
| toUpperCase(Locale) | O(n) | O(n) | Locale-sensitive uppercase conversion |
Always store the result of
toUpperCase() in a new string because strings are immutable in Java.Trying to change the original string directly without assigning the result of
toUpperCase() to a variable.