How does equals method work on a String Buffer object!

Joined
Apr 2, 2012
Messages
1
Reaction score
0
My program is:
Code:
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?
 
Joined
Apr 25, 2017
Messages
247
Reaction score
31
Because you have this line which read all the words in file Word.txt
Code:
StringBuffer strLine = new StringBuffer(br.readLine());
 
Joined
Dec 10, 2020
Messages
10
Reaction score
1
Hello,
StringBuffer sb= new StringBuffer("Java");
StringBuffer sb1 = new StringBuffer("Java");
System.out.println(sb1.equals(sb2));
The above code will work to check the value of the objects.
Thanks
David jack
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,480
Members
44,900
Latest member
Nell636132

Latest Threads

Top