import java.util.Scanner;
public class StringReverser {
public static void main(String[] args) {
// Get input from the user
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
scanner.close();
// Step 2: Reverse the string
String reversedString = reverseString(inputString);
// Step 3: Display the reversed string
System.out.println("The reversed string is: " + reversedString);
// Step 4: Compare strings
compareStrings(inputString, reversedString);
}
// Function to reverse a string
private static String reverseString(String original) {
StringBuilder reversed = new StringBuilder();
for (int i = original.length() - 1; i >= 0; i--) {
reversed.append(original.charAt(i));
}
return reversed.toString();
}
// Function to compare two strings
private static void compareStrings(String str1, String str2) {
// 1st way: Using equals() method (exact equality)
boolean isEqual1 = str1.equals(str2);
System.out.println("Using equals() method: Strings are equal? " + isEqual1);
// 2nd way: Using equalsIgnoreCase() method
boolean isEqual2 = str1.equalsIgnoreCase(str2);
System.out.println("Using equalsIgnoreCase() method: Strings are equal? " + isEqual2);
// 3rd way: Using compareTo() method
int comparisonResult = str1.compareTo(str2);
System.out.println("Using compareTo() method: Comparison result: " + comparisonResult);
}
}
Want 1 to 1 personalized Java training? Email me at isingh30 AT gmail please. View my following video
:
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.