StringBuffer substring Java Pass By Reference

StringBuffer substring Java Pass By Reference


StringBuffer substring Java Pass By Reference

Many petty methods exist with StringBuffer like substring(), setLength() and trimToSize() etc. These methods are not much used in regular programming.


StringBuffer substring Java Pass By Reference

Output screen of MiscellaneousMethods.java


Output screen of MiscellaneousMethods.java of StringBuffer substring Java Pass By Reference

substring() method works the same way of strings. setLength() and trimTosize() do different jobs. Using setLength() method programmer can delete any extra unwanted text (content) in the buffer. Text will be cut off but not the buffer capacity. To cut the extra buffer capacity than required, use trimToSize() method. The above output clearly explains.

Pass-By-Reference

Java supports pass-by-reference through object assignment. Objects are passed as arguments. We know earlier, when objects are assigned one to another, they refer the same location of data. Pass-by-reference is illustrated with StringBuffer.

StringBuffer substring Java Pass By Reference

Output screen of PBRDemo.java


Output screen of PBRDemo.java of StringBuffer substring Java Pass By Reference

Observe, the show() method requires an object of StringBuffer as parameter (not a data type). From the main(), for show() method buffer1 object is passed and is assigned implicitly to buffer2. Now buffer1 and buffer2 refer the same location. When buffer1 value changes buffer2 also gets affected or vice versa. The same thing happended here. buffer2 is appended with Morning which affects buffer2 also (infact they refer the same location). For this reason buffer1 from main() method displayed GoodMorning. It is exactly the same thing we achieved in C/C++ using pass-by-reference or call-by-reference.

Pass-by-reference is also explained with examples of array objects – Passing Arrays to Methods and Passing Arrays to Constructor.

StringBuilder

StringBuilder is explained in comparison with String and StringBuffer with an example.

StringTokenizer

StringTokenizer is explained clearly in java.util package.

Pass your comments and suggestions to improve the quality of this tutorial "StringBuffer substring setLength Pass By Reference"

2 thoughts on “StringBuffer substring Java Pass By Reference

  1. Satya

    Hi Sir,
    I am ardent follower of your courses on Core Java and I improve myself every time with them. Thanks a lot in this regard. I am aspiring for Java Certified Associate Java SE 7 Programmer certification. Will you please let me know what to look for more for cracking it?

Leave a Reply

Your email address will not be published. Required fields are marked *