Convert a String to Uppercase and Lowercase in Java

Topic: Convert a String to Uppercase and Lowercase

In this Java interview program, you'll learn how to convert a string to uppercase and lowercase using simple built-in methods. This is a basic string manipulation task often asked to assess familiarity with the String class and method usage.

Java provides two useful methods for this:

  • toUpperCase(): Converts all characters to uppercase.
  • toLowerCase(): Converts all characters to lowercase.

Examples

  • Input: "Hello World" → Uppercase: "HELLO WORLD", Lowercase: "hello world"
  • Input: "Java123" → Uppercase: "JAVA123", Lowercase: "java123"
  • Edge Case Input: "" → Uppercase: "", Lowercase: ""

Note that numbers and symbols remain unchanged during case conversion.

Interviewer Expectations

The interviewer is checking whether the candidate:

  • Understands how to manipulate strings in Java.
  • Is familiar with Java’s built-in String methods.
  • Can write a clean and simple program using standard Java syntax.

Approach

The solution is straightforward and ideal for beginners:

  1. Accept a string (hardcoded or user input).
  2. Use toUpperCase() and toLowerCase() methods to transform the string.
  3. Print the converted results.

Dry Run

Let's take the input "Welcome123":

  • Uppercase: "WELCOME123"
  • Lowercase: "welcome123"

Java Program

public class CaseConverter {
    public static void main(String[] args) {
        String originalText = "Hello Java 123!";
        String upperText = originalText.toUpperCase();
        String lowerText = originalText.toLowerCase();

        System.out.println("Uppercase: " + upperText);
        System.out.println("Lowercase: " + lowerText);
    }
}
Uppercase: HELLO JAVA 123!
Lowercase: hello java 123!

Possible Followup Questions with Answers

Q1. What happens if the string is already in uppercase?

Answer: Nothing changes. The toUpperCase() method will return the same string as input.

Q2. Do these methods modify the original string?

Answer: No. String in Java is immutable. These methods return new string objects.

Q3. How do you handle user input instead of hardcoded strings?

Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = sc.nextLine();
System.out.println(input.toUpperCase());
System.out.println(input.toLowerCase());

Q4. How would you convert only the first letter to uppercase?

String input = "java";
String result = input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase();
System.out.println(result); // Output: Java

Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...