• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

String conversion and StringBuffer

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

I am confused about what is probably basic behavior re StringBuffer. I've consulted Bates and Sierra as well as Thinking In Java and have probably found but not understood the answer to a question I've encountered on a practice exam.

Code:

1. String x1 = "12ab";
2. StringBuffer bc = new StringBuffer("34cd");
3. byte y = 1;
4. System.out.println(x1 + y);
5. System.out.println(bc + y);

The correct answer to this practice question is that String conversion does not apply to StringBuffer.

I do not see where conversion is trying to take place for the StringBuffer object. I answered is that 12ab is printed on one line followed by 34cd on the next line.

Does not line 5 simply append the value of y and print 1abcd?

Thanks,

:-)

JerryB
 
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The StringBuffer class does not inherit from the String class so in order to use the + operator, you need a String representation of the String Buffer class. To make this work, the statement should be:




(Corrected teeny weeny itsy bitsy syntax error - Barry )
[ June 27, 2004: Message edited by: Barry Gaunt ]
 
Enthuware Software Support
Posts: 4810
52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
To invoke the "overloaded" behavior of the + operator, at least one of the operands must be a String. Otherwise, the + operator tries to do an arithmatic addition. StringBuffer is neither a String nor something which makes sense for arithmatic addition, so if one operand of + is a StringBuffer, other has to be a String.
 
Jerry Bustamente
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you Chris and Paul for your answers.

Very appreciated.

:-)

Jerry Bustamente
 
reply
    Bookmark Topic Watch Topic
  • New Topic