how to compare sb and s
StringBuffer sb= new StringBuffer("Hello");
String s= "Hello";
s.equals(sb.toString()) is giving result as false.
Unable to reproduce:
public class Test {
public static void main(String[] args) {
StringBuffer sb= new StringBuffer("Hello");
String s= "Hello";
System.out.println(s.equals(sb.toString())); // Prints true
}
}
If you think the two values are really the same, please post a similar short but complete program demonstrating the problem. I suspect you'll find the problem is elsewhere - such as some invisible characters in the string or StringBuffer.
use s.contentEquals(sb);
This will work .
Equals and == will not work for comparision of StringBuffer and String.
== will work only for comparisions among the same non-collections [ integers, characters etc.]
equals method will work only for comparisons among the same collections [ array, string, objects etc.]
Note : Comparisions between different collections or non-collection leads to error.
class ClassName{
public static void main(String[] args) {
// STRING VS STRING BUFFER
String strg = "Hello";
StringBuffer strgBuf = new StringBuffer(strg);
//if(strg == strgBuf ) //=> error: incomparable types: String and StringBuffer
if(strg.equals(strgBuf))
System.out.println("strg.equals(strgBuf) is true");
else
System.out.println("strg.equals(strgBuf) is false") ;
//=> strg.equals(strgBuf) is false
// 2 STRINGS COMPARED
if(strg.equals(strgBuf.toString()))
System.out.println("strg.equals(strgBuf.toString()) is true");
else
System.out.println("strg.equals(strgBuf.toString()) is false");
//=> strg.equals(strgBuf.toString()) is true
// STRING BUFFER VS STRING BUFFER
StringBuffer strgBuf2 = new StringBuffer(strg);
if(strgBuf2 == strgBuf)
System.out.println("strgBuf2 == strgBuf is true");
else
System.out.println("strgBuf2 == strgBuf is false") ;
//=> strgBuf2 == strgBuf is false
if(strgBuf2.equals(strgBuf))
System.out.println("strgBuf2.equals(strgBuf) is true");
else
System.out.println("strgBuf2.equals(strgBuf) is false") ;
//=> strgBuf2.equals(strgBuf) is false
// 2 STRINGS COMPARED
if(strgBuf2.toString().equals(strgBuf.toString()))
System.out.println("strgBuf2.toString().equals(strgBuf.toString()) is true");
else
System.out.println("strgBuf2.toString().equals(strgBuf.toString()) is false") ;
//=> strgBuf2.toString().equals(strgBuf.toString()) is true
// STRING VS STRING
String strg2 = new String(strg);
if(strg == strg2)
System.out.println("strg == strg2 is true");
else
System.out.println("strg == strg2 is false") ;
//=> strg == strg2 is false
if(strg.equals(strg2))
System.out.println("strg.equals(strg2) is true");
else
System.out.println("strg.equals(strg2) is false") ;
//=> strg.equals(strg2) is true
}
}
equalsIgnoreCase(), if it goes true then there is something about the casing of one of the values.