Win a copy of Event Streams in Action this week in the Java in General forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

String and StringBuffer

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following code resides in the source?
class StringTest {
public static void main( String [] agrs) {
//
// String comparing
//
String a,b;
StringBuffer c,d;
c = new StringBuffer("Hello");
a = new String("Hello");
b = a;
d = c;
if ( <<<operator>>> ) { }
}
} //class
Which of the following statement return true for the <<>> line in StringTest.class?
b.equals(a)
b==a
d==c
d.equals(c)
The answer is a, b, c, d that is all are correct ...I think the last one is not correct as StringBuffer don't override the equals() method..any explanation.........
Wali
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi WaliM,
StringBuffer does not override the equals method but the inherited equals method of Object compares object references. since c and d point to the same object the answer is true. If however d is a new object like the one created in the code below then u r right in u r answer.
class StringTest {
public static void main( String [] agrs) {
//
// String comparing
//
String a,b;
StringBuffer c,d;
c = new StringBuffer("Hello");
a = new String("Hello");
b = a;
d = new StringBuffer("Hello");
if (d==c )
System.out.println("True");
else
System.out.println("False");

}
}
The code above prints False
Regds.
Rahul.

Regards.
Rahul.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot rahul
Wali
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!