Java Program to Convert a String to Uppercase
Introduction
Converting a string to uppercase is a basic 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 uppercase.
Problem Statement
Create a Java program that:
- Prompts the user to enter a string.
- Converts the entire string to uppercase.
- Displays the uppercase string.
Example:
- Input:
"hello world"
- Output:
"HELLO WORLD"
Solution Steps
- Read the String: Use the
Scanner
class to take the string as input from the user. - Convert the String to Uppercase: Use the
toUpperCase()
method to convert the string to uppercase. - Display the Uppercase String: Print the converted string.
- Close Resources: Close the
Scanner
class object automatically using the try-resource statement.
Java Program
// Java Program to Convert a String to Uppercase
import java.util.Scanner;
public class StringToUppercase {
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 uppercase
String uppercaseString = input.toUpperCase();
// Step 3: Display the uppercase string
System.out.println("Uppercase string: " + uppercaseString);
}
}
}
Explanation
Step 1: Read the String
- The
Scanner
class 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 Uppercase
- The
toUpperCase()
method of theString
class is used to convert the entire string to uppercase.
Step 3: Display the Uppercase String
- The program prints the converted uppercase string using
System.out.println()
.
Output
Enter a string: hello world
Uppercase string: HELLO WORLD
Conclusion
This Java program demonstrates how to convert a user-input string to uppercase. It covers essential concepts such as string manipulation and using built-in methods, making it a valuable exercise for beginners learning Java programming.