1
import java.lang.*;
class hello
{
    public static void main(String args[])
    {
         StringBuffer s3 = new StringBuffer("R");
         String s1 = "Rahul";
         char ch = s1.charAt(0);
         System.out.println(s3.toString().equals(ch));
    }
}

Output should be TRUE but it is showing false. Please help.

3
  • @Juvanis: It compiles as per String.equals(Object param) and autoboxing of char to Character. param is not limited to String. Commented Mar 31, 2013 at 8:57
  • @Steph just noticed that, sorry. =) Commented Mar 31, 2013 at 8:57
  • Also, prefer StringBuilder to StringBuffer. Commented Mar 31, 2013 at 9:30

4 Answers 4

4

Most ovverridings of equals don't return true if the types aren't the same.

String's equals implementation is like this :

1012    public boolean equals(Object anObject) {
1013        if (this == anObject) {
1014            return true;
1015        }
1016        if (anObject instanceof String) {
               ...
1030        }
1031        return false;
1032    }

Here, you're comparing a String and a Character (due to autoboxing, as an Object is needed).

What you can do is ensure you're comparing a string to a string :

    System.out.println(s3.toString().equals(""+ch));

or simply compare the characters, as you know ch is a character :

    System.out.println(s3.charAt(0)==ch);
Sign up to request clarification or add additional context in comments.

Comments

1

It is not related to StringBuffer, it is because you compare th String "R" to the char 'R'

Comments

1

You are comparing the string "R" to the character 'R' which according to Java isn't equal, because the types do not match.

Comments

0

You are checking equality between a String (s2.toString()) and a Character (ch) . So, it is returning false . For equality check you should first typecase that char to String . You can use the following code:

System.out.println(s3.toString().equals(String.valueOf(ch)));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.