Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
I am learning GoF Java Design Patterns and I want to see some real life examples of them. Can you guys point to some good usage of these Design Patterns.(preferably in Java's core libraries). Thank you
What is the main difference between StringBuffer and StringBuilder? Is there any performance issues when deciding on any one of these?
Please tell me a real time situation to compare String, StringBuffer, and StringBuilder?
Is there a C++ Standard Template Library class that provides efficient string concatenation functionality, similar to C#'s StringBuilder or Java's StringBuffer?
While working in a Java app, I recently was needing to assemble a comma-delimited list of values to pass to another web service without knowing how many elements there would be in advance. The best I could come up with off the top of my head was something like this: public String appendWithDelimiter( String original, String addition, String delimiter ) { if ( original.equals( "" ) ) { retur...
I'm pasting this text from an ebook I have. It says the complexity if O(n2) and also gives an explanation for it, but I fail to see how. Question: What is the running time of this code? public String makeSentence(String[] words) { StringBuffer sentence = new StringBuffer(); for (String w : words) sentence.append(w); return sentence.toString(); } The answer the book gave: O(n^2), where n...
Is there any facility in the standard Java libraries that, given a CharSequence, produces the reverse in O(1) time? I guess this is "easy" to implement, just wondering whether it already exists. (I suspect the reason this is not offered is because the "easy" way would actually break multi-char code-points - but in many cases we know we are not dealing with those). Thanks Update Heh, it's a...
A friend gave me this piece of code and said there is a bug. And yes, this code runs for ever. The answer I got is: It runs for >10^15 years before printing anything. public class Match { public static void main(String[] args) { Pattern p = Pattern.compile("(aa|aab?)+"); int count = 0; for(String s = ""; s.length() < 200; s += "a") if (p.ma...
I have a program I ported from C to Java. Both apps use quicksort to order some partitioned data (genomic coordinates). The Java version runs fast, but I'd like to get it closer to the C version. I am using the Sun JDK v6u14. Obviously I can't get parity with the C application, but I'd like to learn what I can do to eke out as much performance as reasonably possible (within the limits of the...
Someone told me it's more efficient to use StringBuffer to concatenate strings in Java than to use the + operator for Strings. What happens under the hood when you do that? What does StringBuffer do differently?
I have an HttpResponse object for a web request I just made. The response is in the JSON format, so I need to parse it. I can do it in an absurdly complex way, but it seems like there must be a better way. Is this really the best I can do? HttpResponse response; // some response object Reader in = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), "U...
In my quest to correctly grasp Interface best practices, I have noticed declarations such as: List<String> myList = new ArrayList<String>(); instead of ArrayList<String> myList = new ArrayList<String>(); -To my understanding the reason is because it allows flexibility in case one day you do not want to implement an ArrayList but maybe another type of list. With t...
I think I understand StringIO somewhat as being similar to java's StringBuffer class, but I don't really understand it fully. How would you define it and it's purpose/possible uses in ruby? Just hoping to clear up my confusion. Thanks
Strings are immutable, meaning, once they have been created they cannot be changed. So, does this mean that it would take more memory if you append things with += than if you created a StringBuffer and appended text to that? If you use +=, you would create a new 'object' each time that has to be saved in the memory, wouldn't you?
When I run this code: StringBuffer name = new StringBuffer("stackoverflow.com"); System.out.println("Length: " + name.length() + ", capacity: " + name.capacity()); it gives output: Length: 17, capacity: 33 Obvious length is related to number of characters in string, but I am not sure what capacity is? Is that number of characters that StringBuffer can hold before reallocating space?
I was reading the documentation for StringBuffer, in particular the reverse() method: Javadoc Link Here. In there it mentioned something about "surrogate pairs". What is a surrogate pair in this context? What are low and high surrogates? Thanks.
I am not able to understand the following behavior of StringBuilder when NULL objects are appended to an instance: public class StringBufferTest { /** * @param args */ public static void main(String[] args) { String nullOb = null; StringBuilder lsb = new StringBuilder(); lsb.append("Hello World"); System.out.println("Length is: " + lsb.length...
Suppose our application have only one thread. and we are using StringBuffer then what is the problem? I mean if StringBuffer can handle multiple threads through synchronization, what is the problem to work with single thread? Why use StringBuilder instead?
can somebody explain me why it's possible to do: String s = "foo"; how is this possible without operator overloading (in that case the "=") I'm from a C++ background so that explains...
Is there a way to convert a byte array to string other than using new String(bytearray)? The exact problem is I transmit a json-formatted string over the network through UDP connection. At the other end, I receive it in a fixed-size byte array(as I am not aware of the array size) and create a new string out of the byte array. If I do this, the whole memory that I allocated is being held unnece...
How do you clear the string buffer in Java after a loop so the next iteration uses a clear string buffer?
  /*
   * Copyright 1994-2004 Sun Microsystems, Inc.  All Rights Reserved.
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   *
   * This code is free software; you can redistribute it and/or modify it
   * under the terms of the GNU General Public License version 2 only, as
   * published by the Free Software Foundation.  Sun designates this
   * particular file as subject to the "Classpath" exception as provided
   * by Sun in the LICENSE file that accompanied this code.
  *
  * This code is distributed in the hope that it will be useful, but WITHOUT
  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  * version 2 for more details (a copy is included in the LICENSE file that
  * accompanied this code).
  *
  * You should have received a copy of the GNU General Public License version
  * 2 along with this work; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  *
  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  * CA 95054 USA or visit www.sun.com if you need additional information or
  * have any questions.
  */
 
 package java.lang;


A thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.

String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved.

The principal operations on a StringBuffer are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string buffer. The append method always adds these characters at the end of the buffer; the insert method adds the characters at a specified point.

For example, if z refers to a string buffer object whose current contents are "start", then the method call z.append("le") would cause the string buffer to contain "startle", whereas z.insert(4, "le") would alter the string buffer to contain "starlet".

In general, if sb refers to an instance of a StringBuffer, then sb.append(x) has the same effect as sb.insert(sb.length(), x).

Whenever an operation occurs involving a source sequence (such as appending or inserting from a source sequence) this class synchronizes only on the string buffer performing the operation, not on the source.

Every string buffer has a capacity. As long as the length of the character sequence contained in the string buffer does not exceed the capacity, it is not necessary to allocate a new internal buffer array. If the internal buffer overflows, it is automatically made larger. As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread, StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.

Author(s):
Arthur van Hoff
Since:
JDK1.0
See also:
StringBuilder
String
 
  public final class StringBuffer
     extends AbstractStringBuilder
     implements java.io.SerializableCharSequence
 {

    
use serialVersionUID from JDK 1.0.2 for interoperability
 
     static final long serialVersionUID = 3388685877147921107L;

    
Constructs a string buffer with no characters in it and an initial capacity of 16 characters.
 
     public StringBuffer() {
         super(16);
     }

    
Constructs a string buffer with no characters in it and the specified initial capacity.

Parameters:
capacity the initial capacity.
Throws:
NegativeArraySizeException if the capacity argument is less than 0.
    public StringBuffer(int capacity) {
        super(capacity);
    }

    
Constructs a string buffer initialized to the contents of the specified string. The initial capacity of the string buffer is 16 plus the length of the string argument.

Parameters:
str the initial contents of the buffer.
Throws:
NullPointerException if str is null
    public StringBuffer(String str) {
        super(str.length() + 16);
        append(str);
    }

    
Constructs a string buffer that contains the same characters as the specified CharSequence. The initial capacity of the string buffer is 16 plus the length of the CharSequence argument.

If the length of the specified CharSequence is less than or equal to zero, then an empty buffer of capacity 16 is returned.

Parameters:
seq the sequence to copy.
Throws:
NullPointerException if seq is null
Since:
1.5
    public StringBuffer(CharSequence seq) {
        this(seq.length() + 16);
        append(seq);
    }
    public synchronized int length() {
        return ;
    }
    public synchronized int capacity() {
        return .;
    }
    public synchronized void ensureCapacity(int minimumCapacity) {
        if (minimumCapacity > .) {
            expandCapacity(minimumCapacity);
        }
    }

    

Since:
1.5
    public synchronized void trimToSize() {
        super.trimToSize();
    }

    
    public synchronized void setLength(int newLength) {
        super.setLength(newLength);
    }

    
    public synchronized char charAt(int index) {
        if ((index < 0) || (index >= ))
            throw new StringIndexOutOfBoundsException(index);
        return [index];
    }

    

Since:
1.5
    public synchronized int codePointAt(int index) {
        return super.codePointAt(index);
    }

    

Since:
1.5
    public synchronized int codePointBefore(int index) {
        return super.codePointBefore(index);
    }

    

Since:
1.5
    public synchronized int codePointCount(int beginIndexint endIndex) {
        return super.codePointCount(beginIndexendIndex);
    }

    

Since:
1.5
    public synchronized int offsetByCodePoints(int indexint codePointOffset) {
        return super.offsetByCodePoints(indexcodePointOffset);
    }

    
    public synchronized void getChars(int srcBeginint srcEndchar dst[],
                                      int dstBegin)
    {
        super.getChars(srcBeginsrcEnddstdstBegin);
    }

    
    public synchronized void setCharAt(int indexchar ch) {
        if ((index < 0) || (index >= ))
            throw new StringIndexOutOfBoundsException(index);
        [index] = ch;
    }

    
    public synchronized StringBuffer append(Object obj) {
        super.append(String.valueOf(obj));
        return this;
    }
    public synchronized StringBuffer append(String str) {
        super.append(str);
        return this;
    }

    
Appends the specified StringBuffer to this sequence.

The characters of the StringBuffer argument are appended, in order, to the contents of this StringBuffer, increasing the length of this StringBuffer by the length of the argument. If sb is null, then the four characters "null" are appended to this StringBuffer.

Let n be the length of the old character sequence, the one contained in the StringBuffer just prior to execution of the append method. Then the character at index k in the new character sequence is equal to the character at index k in the old character sequence, if k is less than n; otherwise, it is equal to the character at index k-n in the argument sb.

This method synchronizes on this (the destination) object but does not synchronize on the source (sb).

Parameters:
sb the StringBuffer to append.
Returns:
a reference to this object.
Since:
1.4
    public synchronized StringBuffer append(StringBuffer sb) {
        super.append(sb);
        return this;
    }


    
Appends the specified CharSequence to this sequence.

The characters of the CharSequence argument are appended, in order, increasing the length of this sequence by the length of the argument.

The result of this method is exactly the same as if it were an invocation of this.append(s, 0, s.length());

This method synchronizes on this (the destination) object but does not synchronize on the source (s).

If s is null, then the four characters "null" are appended.

Parameters:
s the CharSequence to append.
Returns:
a reference to this object.
Since:
1.5
    public StringBuffer append(CharSequence s) {
        // Note, synchronization achieved via other invocations
        if (s == null)
            s = "null";
        if (s instanceof String)
            return this.append((String)s);
        if (s instanceof StringBuffer)
            return this.append((StringBuffer)s);
        return this.append(s, 0, s.length());
    }

    

Throws:
IndexOutOfBoundsException
Since:
1.5
    public synchronized StringBuffer append(CharSequence sint startint end)
    {
        super.append(sstartend);
        return this;
    }
    public synchronized StringBuffer append(char str[]) {
        super.append(str);
        return this;
    }
    public synchronized StringBuffer append(char str[], int offsetint len) {
        super.append(stroffsetlen);
        return this;
    }

    
    public synchronized StringBuffer append(boolean b) {
        super.append(b);
        return this;
    }
    public synchronized StringBuffer append(char c) {
        super.append(c);
        return this;
    }

    
    public synchronized StringBuffer append(int i) {
        super.append(i);
        return this;
    }

    

Since:
1.5
    public synchronized StringBuffer appendCodePoint(int codePoint) {
        super.appendCodePoint(codePoint);
        return this;
    }

    
    public synchronized StringBuffer append(long lng) {
        super.append(lng);
        return this;
    }

    
    public synchronized StringBuffer append(float f) {
        super.append(f);
        return this;
    }

    
    public synchronized StringBuffer append(double d) {
        super.append(d);
        return this;
    }

    
    public synchronized StringBuffer delete(int startint end) {
        super.delete(startend);
        return this;
    }

    
    public synchronized StringBuffer deleteCharAt(int index) {
        super.deleteCharAt(index);
        return this;
    }

    
    public synchronized StringBuffer replace(int startint endString str) {
        super.replace(startendstr);
        return this;
    }

    
    public synchronized String substring(int start) {
        return substring(start);
    }

    

Throws:
IndexOutOfBoundsException
Since:
1.4
    public synchronized CharSequence subSequence(int startint end) {
        return super.substring(startend);
    }

    
    public synchronized String substring(int startint end) {
        return super.substring(startend);
    }

    
    public synchronized StringBuffer insert(int indexchar str[], int offset,
                                            int len)
    {
        super.insert(indexstroffsetlen);
        return this;
    }

    
    public synchronized StringBuffer insert(int offsetObject obj) {
        super.insert(offset, String.valueOf(obj));
        return this;
    }

    
    public synchronized StringBuffer insert(int offsetString str) {
        super.insert(offsetstr);
        return this;
    }

    
    public synchronized StringBuffer insert(int offsetchar str[]) {
        super.insert(offsetstr);
        return this;
    }

    

Throws:
IndexOutOfBoundsException
Since:
1.5
    public StringBuffer insert(int dstOffsetCharSequence s) {
        // Note, synchronization achieved via other invocations
        if (s == null)
            s = "null";
        if (s instanceof String)
            return this.insert(dstOffset, (String)s);
        return this.insert(dstOffsets, 0, s.length());
    }

    

Throws:
IndexOutOfBoundsException
Since:
1.5
    public synchronized StringBuffer insert(int dstOffsetCharSequence s,
                                            int startint end)
    {
        super.insert(dstOffsetsstartend);
        return this;
    }

    
    public StringBuffer insert(int offsetboolean b) {
        return insert(offset, String.valueOf(b));
    }

    
    public synchronized StringBuffer insert(int offsetchar c) {
        super.insert(offsetc);
        return this;
    }

    
    public StringBuffer insert(int offsetint i) {
        return insert(offset, String.valueOf(i));
    }

    
    public StringBuffer insert(int offsetlong l) {
        return insert(offset, String.valueOf(l));
    }

    
    public StringBuffer insert(int offsetfloat f) {
        return insert(offset, String.valueOf(f));
    }

    
    public StringBuffer insert(int offsetdouble d) {
        return insert(offset, String.valueOf(d));
    }

    

Throws:
NullPointerException
Since:
1.4
    public int indexOf(String str) {
        return indexOf(str, 0);
    }

    

Throws:
NullPointerException
Since:
1.4
    public synchronized int indexOf(String strint fromIndex) {
        return String.indexOf(, 0, ,
                              str.toCharArray(), 0, str.length(), fromIndex);
    }

    

Throws:
NullPointerException
Since:
1.4
    public int lastIndexOf(String str) {
        // Note, synchronization achieved via other invocations
        return lastIndexOf(str);
    }

    

Throws:
NullPointerException
Since:
1.4
    public synchronized int lastIndexOf(String strint fromIndex) {
        return String.lastIndexOf(, 0, ,
                              str.toCharArray(), 0, str.length(), fromIndex);
    }

    

Since:
JDK1.0.2
    public synchronized StringBuffer reverse() {
        super.reverse();
        return this;
    }
    public synchronized String toString() {
        return new String(, 0, );
    }

    
Serializable fields for StringBuffer.

SerialField:
value char[] The backing character array of this StringBuffer.
SerialField:
count int The number of characters in this StringBuffer.
SerialField:
shared boolean A flag indicating whether the backing array is shared. The value is ignored upon deserialization.
    private static final java.io.ObjectStreamField[] serialPersistentFields =
    {
        new java.io.ObjectStreamField("value"char[].class),
        new java.io.ObjectStreamField("count".),
        new java.io.ObjectStreamField("shared".),
    };

    
readObject is called to restore the state of the StringBuffer from a stream.
    private synchronized void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {
        java.io.ObjectOutputStream.PutField fields = s.putFields();
        fields.put("value");
        fields.put("count");
        fields.put("shared"false);
        s.writeFields();
    }

    
readObject is called to restore the state of the StringBuffer from a stream.
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOExceptionClassNotFoundException {
        java.io.ObjectInputStream.GetField fields = s.readFields();
         = (char[])fields.get("value"null);
         = fields.get("count", 0);
    }
New to GrepCode? Check out our FAQ X