How does equals method work on a String Buffer object!

Discussion in 'Java' started by javabeginner29, Apr 2, 2012.

  1. javabeginner29

    javabeginner29

    Joined:
    Apr 2, 2012
    Messages:
    1
    Likes Received:
    0
    My program is:
    Code (Text):
    import java.io.*;
    class Palindrome
    {
        public static void main(String args[])
        {
            try{
                // Open the file that is the first
                // command line parameter
                FileInputStream fstream = new FileInputStream("Words.txt");
                // Get the object of DataInputStream
                DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
               
                while(br.readLine()!= null){
                StringBuffer strLine = new StringBuffer(br.readLine());
                   
                    String str1 = strLine.toString();
                    String str2 = strLine.reverse().toString();
                   
               
                if (str1.equals(str2)) {
                     
                    System.out.println(str1 + " is  a palindrome");
                }
                }
               
               
                //Close the input stream
                in.close();
            }catch (Exception e){//Catch exception if any
                System.err.println("Error: " + e.getMessage());
            }
        }
    }
    This program checks if a string is a palindrome by reading each word which is on a different line from the file Word.txt. This works .. But my question is :

    when I give if(strLine.equals(strLine.reverse()) it doesnot give the desired output. It simply prints all the words in the file Word.txt concatenated with " is a palindrome". Why is it so?
     
    javabeginner29, Apr 2, 2012
    #1
    1. Advertisements

  2. javabeginner29

    John Joe

    Joined:
    Apr 25, 2017
    Messages:
    97
    Likes Received:
    14
    Location:
    Malaysia
    Because you have this line which read all the words in file Word.txt
    Code (Text):
    StringBuffer strLine = new StringBuffer(br.readLine());
     
    John Joe, Jul 5, 2018
    #2
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.