Develop a Java program that performs two essential string manipulation tasks:
- Convert a given string to lowercase.
- Convert a given string to uppercase.
- Method Signature:
public static String toLowerCase(String value)
- Description:
- This method converts the given string into lowercase without using built-in string manipulation methods.
- Method Signature:
public static String toUpperCase(String value)
- Description:
- This method converts the given string into uppercase without using built-in string manipulation methods.
- Method Signature:
public static void main(String[] args)
- Functionality:
- Prompt the user to input a string.
- Call toLowerCase() to convert the string to lowercase.
- Call toUpperCase() to convert the string to uppercase.
- Display both the lowercase and uppercase results.
- The program should handle all possible string inputs without restrictions.
- Do not use built-in string manipulation methods such as
toLowerCase()
,toUpperCase()
,substring()
, ortoCharArray()
. - The only allowed method from the String class is
length()
. - You must use loops (
for
orwhile
) to iterate through the string and manipulate characters.
Hints: Using HashMap
for Character Conversion
Why Use HashMap
?
A HashMap
is an efficient way to store character mappings because:
- It provides O(1) lookup time, making conversions fast.
- It allows us to map uppercase letters (
A-Z
) to lowercase (a-z
) and vice versa.
- In ASCII, uppercase and lowercase letters differ by 32:
'A' (65)
→'a' (97)
,'B' (66)
→'b' (98)
, etc.- Lowercase letters (
a-z
) can be mapped back to uppercase using the same logic.
Steps to Implement Using HashMap
-
Create Two
HashMap
ObjectslowerMap
: Maps uppercase letters (A-Z
) to lowercase (a-z
).upperMap
: Maps lowercase letters (a-z
) to uppercase (A-Z
).
-
Populate the Maps
- Iterate through uppercase letters (
A-Z
), mapping each to its lowercase counterpart. - Repeat for lowercase letters (
a-z
), mapping them to uppercase.
- Iterate through uppercase letters (
-
Perform the Conversion
- Iterate through the string, checking each character in the respective map.
- If a character is found in the map, replace it; otherwise, keep it unchanged.
Alternative Approach Without HashMap
- If
HashMap
is not used, the conversion can be done using ASCII arithmetic:- If a character is between
'A'
and'Z'
, add32
to convert it to lowercase. - If a character is between
'a'
and'z'
, subtract32
to convert it to uppercase.
- If a character is between