Introduction
Converting a string to lowercase is a common operation in text processing. This task helps you understand how to manipulate strings using built-in methods in Java. This guide will walk you through writing a Java program that converts a given string to lowercase.
Problem Statement
Create a Java program that:
- Prompts the user to enter a string.
- Converts the entire string to lowercase.
- Displays the lowercase string.
Example:
- Input: "HELLO WORLD"
- Output: "hello world"
Solution Steps
- Read the String: Use the Scannerclass to take the string as input from the user.
- Convert the String to Lowercase: Use the toLowerCase()method to convert the string to lowercase.
- Display the Lowercase String: Print the converted string.
Java Program
// Java Program to Convert a String to Lowercase
// Author: https://www.rameshfadatare.com/
import java.util.Scanner;
public class StringToLowercase {
  public static void main(String[] args) {
    // Step 1: Read the string from the user
    try (Scanner scanner = new Scanner(System.in)) {
      System.out.print("Enter a string: ");
      String input = scanner.nextLine();
      // Step 2: Convert the string to lowercase
      String lowercaseString = input.toLowerCase();
      // Step 3: Display the lowercase string
      System.out.println("Lowercase string: " + lowercaseString);
    }
  }
}
Explanation
Step 1: Read the String
- The Scannerclass is used to read a string input from the user. ThenextLine()method captures the entire line as a string.
Step 2: Convert the String to Lowercase
- The toLowerCase()method of theStringclass is used to convert the entire string to lowercase.
Step 3: Display the Lowercase String
- The program prints the converted lowercase string using System.out.println().
Output Example
Example:
Enter a string: HELLO WORLD
Lowercase string: hello world
Conclusion
This Java program demonstrates how to convert a user-input string to lowercase. It covers essential concepts such as string manipulation and using built-in methods, making it a valuable exercise for beginners learning Java programming.