Java String.toUpperCase() Method Example

1. Introduction

The String.toUpperCase() method in Java is used to convert all the characters in a string to uppercase. This method is frequently used in scenarios where uniform case is required for comparisons, data processing, or user display purposes. This tutorial will demonstrate how to use toUpperCase() to convert a string to uppercase.

Key Points

- toUpperCase() converts all characters in the string to uppercase.

- It is useful for standardizing text data and enhancing readability in certain contexts.

- The method returns a new string, leaving the original string unchanged.

2. Program Steps

1. Declare a string with mixed case.

2. Convert the string to uppercase.

3. Print the original and the converted string.

3. Code Program

public class StringToUpperCaseExample {
    public static void main(String[] args) {
        // Original string with mixed case
        String original = "Hello, world!";
        // Convert to uppercase
        String uppercased = original.toUpperCase();
        // Print original and uppercase version
        System.out.println("Original: " + original);
        System.out.println("Uppercase: " + uppercased);
    }
}

Output:

Original: Hello, world!
Uppercase: HELLO, WORLD!

Explanation:

1. String original = "Hello, world!": Declares and initializes a String variable original with both uppercase and lowercase letters.

2. String uppercased = original.toUpperCase(): Converts all characters in original to uppercase and assigns the result to uppercased.

3. System.out.println("Original: " + original): Prints the original string.

4. System.out.println("Uppercase: " + uppercased): Prints the new string after conversion to uppercase, demonstrating the effect of the toUpperCase() method.


Comments