Create Your First Character Conversion Program
In this step, you will create a Java program that demonstrates how to convert a character to lowercase using the toLowerCase(char ch) method from Java's Character class.
Understanding Character Case Conversion
In Java, characters are represented by the primitive data type char. The Character class provides various methods to manipulate and work with characters, including the ability to convert between uppercase and lowercase.
The toLowerCase(char ch) method takes a character as input and:
- Returns the lowercase version of the character if it was uppercase
- Returns the same character if it was already lowercase or is not a letter
Creating the Java File
First, let's create a new Java file in the project directory:
- Open the WebIDE editor window
- Navigate to the File menu and click "New File"
- Name the file
CharacterToLowerCase.java and save it in the /home/labex/project directory
Alternatively, you can use the terminal to create the file:
cd ~/project
touch CharacterToLowerCase.java
Writing Your First Program
Now, let's write the code in the CharacterToLowerCase.java file:
- Open the file in the WebIDE editor
- Copy and paste the following code into the file:
public class CharacterToLowerCase {
public static void main(String[] args) {
// Create character variables with different cases
char upperCaseChar = 'A';
char lowerCaseChar = 'b';
char nonLetterChar = '5';
// Convert each character to lowercase
char result1 = Character.toLowerCase(upperCaseChar);
char result2 = Character.toLowerCase(lowerCaseChar);
char result3 = Character.toLowerCase(nonLetterChar);
// Print the original and lowercase characters
System.out.println("Original uppercase character: " + upperCaseChar);
System.out.println("After toLowerCase(): " + result1);
System.out.println();
System.out.println("Original lowercase character: " + lowerCaseChar);
System.out.println("After toLowerCase(): " + result2);
System.out.println();
System.out.println("Original non-letter character: " + nonLetterChar);
System.out.println("After toLowerCase(): " + result3);
}
}
This program demonstrates the toLowerCase(char ch) method with three different types of characters:
- An uppercase letter ('A')
- A lowercase letter ('b')
- A non-letter character ('5')
Compiling and Running the Program
Now, let's compile and run the Java program:
-
Open the terminal in the WebIDE
-
Navigate to the project directory if you're not already there:
cd ~/project
-
Compile the Java file:
javac CharacterToLowerCase.java
-
Run the compiled program:
java CharacterToLowerCase
You should see the following output:
Original uppercase character: A
After toLowerCase(): a
Original lowercase character: b
After toLowerCase(): b
Original non-letter character: 5
After toLowerCase(): 5
As you can see, the uppercase 'A' was converted to lowercase 'a', while the already lowercase 'b' and the non-letter character '5' remained unchanged.