Convert Character to Title Case

JavaJavaBeginner
Practice Now

Introduction

The toTitleCase(char ch) method is a part of the Character class in Java and is used to convert the specified character to titlecase using case mapping information from the UnicodeData file. This method returns the equivalent titlecase character of the input character.

Accept User Input

In order to test the toTitleCase(char ch) method, we need to accept user input. We can do this using the Scanner class provided by Java.

import java.util.Scanner;

public class TitleCaseExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a character: ");
        char ch = scanner.next().charAt(0);

        scanner.close();
    }
}

In this code, we create a new Scanner object to read user input from the terminal. We then prompt the user to enter a character and read the input using the scanner.next().charAt(0) method call. This call reads a string input from the user and returns the first character of that string.

Convert Character to Titlecase

Now that we have the input character, we can convert it to its equivalent titlecase character using the toTitleCase(char ch) method.

import java.util.Scanner;

public class TitleCaseExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a character: ");
        char ch = scanner.next().charAt(0);

        char titlecaseChar = Character.toTitleCase(ch);

        System.out.println("The titlecase equivalent of " + ch + " is " + titlecaseChar);

        scanner.close();
    }
}

In this code, we call the Character.toTitleCase(char ch) method to convert the input character to its equivalent titlecase character. We then print the original character and its titlecase equivalent to the terminal.

Compile and Run the Code

To run the code, we need to compile it first. Open the terminal and navigate to the ~/project directory. Then, compile the code using the following command:

javac TitleCaseExample.java

Once the code is compiled successfully, we can run it using this command:

java TitleCaseExample

Test the Code

Once the code is running, you can enter any character and check its titlecase equivalent. Here are some examples:

Enter a character: a
The titlecase equivalent of a is A
Enter a character: z
The titlecase equivalent of z is Z
Enter a character: 1
The titlecase equivalent of 1 is 1
Enter a character: *
The titlecase equivalent of * is *

Summary

In this lab, you learned how to use the toTitleCase(char ch) method of the Character class to convert characters to their equivalent titlecase characters. You also learned how to accept user input and print output to the terminal using Java code.

Other Java Tutorials you may like