Menu
Topics Index
...
`

Print Palindromes


If you need explanation Read this topic

If you need Answer Take test on this topic

Print Palindromes
What will be the output of the following program?
public class PrintPalindromes {
    public static void main(String s[]) {
        String input = "Malayalam";
        for (int i = 2; i < input.length(); i++) {
            for (int j = 0; j + i < input.length(); j++) {
                if (isPalindrome(input.substring(j, j + i + 1))) {
                    System.out.print(input.substring(j, j + i + 1) + "-");
                }
            }
        }
    }
    public static boolean isPalindrome(String input) {
        return input.equals(new StringBuffer(input).reverse());
    }
}

A. M-a-l-a-y-a-l-a-ala-aya-ala-layal-alayala-
B. M-a-l-a-y-a-l-a-m-ala-aya-ala-layal-alayala-Malayalam-
C. ala-aya-ala-layal-alayala-
D. No output is generated
E. Compilation Error or Runtime Error
Topic: Java StringBuffer, reverse() - Reverse A String In Java

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

D.no output is generated. as if condition wr cllng ispalindrome by reversing and none is matched . so no ouput

Posted by Shabaaz Shaikz    2014-01-16 12:38:52


D.No output is generated

Posted by Sai Madan    2014-01-16 12:47:09


D

Posted by Shravan Kumar    2014-01-16 15:39:14


Although correct answer is D. The explanation is not correct. The method isPalindrome always returns false because we are comparing a String with StringBuffer using equals method. Although the content is same it will return false, since the object types are different. If we pass 'new StringBuffer(input).reverse().toString()' instead then it will give an output 'ala-aya-ala-layal-alayala-'.

Posted by Merit Campus    2014-01-17 03:59:25


No winner for this dose :-)

Posted by Merit Campus    2014-01-17 04:00:00


© meritcampus 2019

All Rights Reserved.

Open In App