This is the fourth solution to find the reverse of an integer or string data value by using the Generics. The internal logic of the Generic method uses the reverse method of StringBuffer class.
import java.util.Scanner;
public class ReverseUsingGenerics {
//Define the Generic Method which takes either integer or string value
private static <T> StringBuffer reverseGeneric(T dataValue) {
// Convert dataValue to String
StringBuffer toStrbuf = new StringBuffer(String.valueOf(dataValue));
return (toStrbuf.reverse());
}
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner inpInt = new Scanner(System.in);
// Input an Integer
System.out.print("Enter an Integer=");
int numValue = inpInt.nextInt();
System.out.println("The given input is=" + numValue);
//Invoke the reverseGeneric() method with integer value
System.out.println("The integer after reverse is="+Integer.parseInt(reverseGeneric(numValue).toString()));
System.out.println();
// Input a String
System.out.print("Enter a String=");
String strValue = inpInt.next();
System.out.println("The given input is=" + strValue);
//Invoke the reverseGeneric() method with String value
System.out.println("The String value after reversing="+reverseGeneric(strValue));
}
}
Output:
Enter an Integer=792
The given input is=792
The integer after reverse is=297
Enter a String=Test
The given input is=Test
The String value after reversing=tseT

Leave a comment