0
0
JavaHow-ToBeginner · 2 min read

Java How to Convert String to Lowercase Example

In Java, you can convert a string to lowercase by using the toLowerCase() method like this: String lower = originalString.toLowerCase();.
📋

Examples

InputHELLO
Outputhello
InputJava Programming
Outputjava programming
Input123 ABC xyz!
Output123 abc xyz!
🧠

How to Think About It

To convert a string to lowercase, think of changing every uppercase letter to its lowercase version while leaving other characters unchanged. Java provides a built-in method toLowerCase() that does this for you easily.
📐

Algorithm

1
Get the original string input.
2
Call the <code>toLowerCase()</code> method on the string.
3
Store or return the new lowercase string.
💻

Code

java
public class LowercaseExample {
    public static void main(String[] args) {
        String original = "Hello World!";
        String lower = original.toLowerCase();
        System.out.println(lower);
    }
}
Output
hello world!
🔍

Dry Run

Let's trace converting "Hello World!" to lowercase.

1

Original String

original = "Hello World!"

2

Convert to Lowercase

lower = original.toLowerCase() -> "hello world!"

3

Print Result

Output: "hello world!"

StepString Value
1Hello World!
2hello world!
3hello world!
💡

Why This Works

Step 1: Use of toLowerCase()

The toLowerCase() method converts all uppercase letters in the string to lowercase.

Step 2: Immutable Strings

Strings in Java are immutable, so toLowerCase() returns a new string without changing the original.

Step 3: Non-letter Characters

Characters that are not letters, like numbers or punctuation, remain unchanged.

🔄

Alternative Approaches

Using Locale with toLowerCase
java
import java.util.Locale;

public class LowercaseLocale {
    public static void main(String[] args) {
        String original = "HELLO WORLD";
        String lower = original.toLowerCase(Locale.ENGLISH);
        System.out.println(lower);
    }
}
This approach is useful to handle locale-specific lowercase rules, ensuring consistent results across different languages.

Complexity: O(n) time, O(n) space

Time Complexity

The method processes each character once, so it takes linear time proportional to the string length.

Space Complexity

A new string is created to hold the lowercase result, so space used is proportional to the string length.

Which Approach is Fastest?

Using toLowerCase() without locale is slightly faster but may cause locale issues; using locale is safer for international apps.

ApproachTimeSpaceBest For
toLowerCase()O(n)O(n)Simple lowercase conversion
toLowerCase(Locale)O(n)O(n)Locale-aware conversion
💡
Always use toLowerCase(Locale.ROOT) if you want locale-independent lowercase conversion.
⚠️
Forgetting that strings are immutable and expecting toLowerCase() to change the original string directly.