Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

JAVA a) Write a method reverse() that accepts a String object as an argument and

ID: 3690920 • Letter: J

Question

JAVA

a) Write a method reverse() that accepts a String object as an argument and displays its contents backward. For example, if the string argument ( entered by user) is….“Hello”, the method should display “olleH”.

-“Hi there”, the method should display “ereht iH”

b)

Palindrome is a sequence of characters/literals which reads the same from forward or backward. Eg:

-“Racecar” is a palindrome as its reverse reads “racecaR” (HINT: Make sure that we are interested in only sequence, so your code should be case insensitive to detect this String as a palindrome)- “kayak” is a palindrome

Write a method palindrome()that accepts the original String and reversed string (output of reverse()) as arguments and displays if original String is a palindrome or not.

Explanation / Answer

a) method to reverse a string

import java.util.*;

class ReverseString {

public static void main(String [ ]args) {

String original, reverse=" ";

Scanner.in=new Scanner(System.in);

System.out.println("Enter a string to reverse");

original=in.nextLine();

int length=original.length();

for(int i=length-1; i>=0; i--)

reverse=reverse+original.charAt(i);

System.out.println("Reverse of entered string is : "+reverse);

}

}

b) method palindrome

import java.util.*;

class Palindrome {

public static void main (String args[]) {

String original,reverse=" ";

Scanner.in= new Scanner(System.in);

System.out.println("Enter a string to check if it is palindrome");

original=in.nextLine();

int length=original.length();

for(int i=length-1; i>=0; i--)

reverse=reverse+original.charAt(i);

if(original.equals(reverse))

System.out.println("Entered String is palindrome");

else

System.out.println("Entered String is not a palindrome");

}

}