Amazon Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
equals is little ambiguous when it comes to StringBuffer.. see the example
public static void main(String[] args) {
String s = new String("hello");
String s2 = s;
System.out.println("1>" + s.equals("hello") + " 2>" + s.equals(s2)
+ " 3>" + (s == s2) + " 4>" + (s == "hello"));
StringBuffer sb = new StringBuffer("hello");
StringBuffer sb2 = sb;
System.out.println("1>" + sb.equals("hello") + " 2>" + sb.equals(sb2)
+ " 3>" + (sb == sb2));
}
o/p:: 1>true 2>true 3>true 4>false
1>false 2>true 3>true
You probably meant 'equals':
- Gagan September 13, 2011The latter (i.e. '==') is used to compare references:
Example:
String str = new String("foo");
if (str == "foo") // This would never return true, because '==' will compare the references (memory locations) and not the content.
Therefore, we use str.equals("foo") // it compares content of the object.