Win a copy of Head First Android this week in the Android 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Rob Spoor
  • Devaka Cooray
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Jj Roberts
  • Al Hobbs
  • Piet Souris

string buffer

 
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi guys,

code:
int a = 0;
StringBuffer s = new StringBuffer("Hello");
if ((s.length() < 10) | (s.append(" world").equals("Well done")))
; // do nothing
System.out.println("Value is - " + s);
in the above code, i thought the result is "Hello",b'cas string buffer doesn't override the equals method, so the result is same as s. but the ans is helloworld, how?
anybody correct me?
thx in advance
 
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
s.append(" world") modifies the content of the StringBuffer s.
 
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

s.length() IS less than 10 -- so that evalutates to true
then things get evaluated from left to right for the 2nd half of the equation:
s.append(" world") -- so at this point s is "Hello world"
s.equals("Well done") -- like you said the .equals method is not overridden in StringBuffer and this half of the equation evalutes to false
But... what would happen if the if statement looked like this:
if ((s.length() < 10) || (s.append(" world").equals("Well done")))
reply
    Bookmark Topic Watch Topic
  • New Topic