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?
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 using a StringBuilder in a loop and every x iterations I want to empty it and start with an empty StringBuilder, but I can't see any method similar to the .Net StringBuilder.Clear in the docs, just the delete method which seems overly complicated. So what is the best way to clean out a StringBuilder in Java?
I have code as follows : String s = ""; for (My my : myList) { s += my.getX(); } Findbugs always reports error when I do this.
I know we can append strings using StringBuilder. Is there a way we can prepend strings (ie: Add strings infront of a string) using StringBuilder so we can keep the performance benefits that StringBuilder offers?
It may seem as if this is question is a dupe, but please bear with me - I promise I've read the related posts (and the GOF book). After everything I've read, I still don't have it clear when to use an Abstract Factory, a Factory Method, or a Builder. I believe it will finally sink in after I see a simple example of a problem which is best approached by, say, a builder and it would be clearly ...
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...
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...
I have something like the following: int i = 3; String someNum = "123"; I'd like to append i "0"'s to the "someNum" string. Does it have some way I can multiply a string to repeat it like Python does? So I could just go: someNum = sumNum + ("0" * 3); or something similar? Where, in this case, my final result would be: "123000".
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...
Possible Duplicates: What’s the best way to build a string of delimited items in Java? Java: convert List<String> to a join()d string In Java, given a collection, getting the iterator and doing a separate case for the first (or last) element and the rest to get a comma separated string seems quite dull, is there something like str.join in Python? Extra clarification fo...
UPDATE: The final version of my utility looks like this: StringBuilder b = new StringBuilder(); for(char c : inLetters.toLowerCase().toCharArray()) { switch(c) { case '0': b.append("0"); break; case '1': b.append("1"); break; case '2': case 'a': case 'b': case 'c': b.append("2"); break; case '3...
Is there a more elegant way of doing this in Java? String value1 = "Testing"; String test = "text goes here " + value1 + " more text"; Is it possible to put the variable directly in the string and have its value evaluated?
How to Improve performance of this chunk of code : public static String concatStrings(Vector strings) { String returnValue = ""; Iterator iter = strings.iterator(); while( iter.hasNext() ) { returnValue += (String)iter.next(); } return returnValue; }
How can we re assign the value of a StringBuffer or StringBuilder Variable? StringBuffer sb=new StringBuffer("teststr"); Now i have to change the value of sb to "testString" without emptying the contents. I am looking at a method which can do this assignment directly without using separate memory allocation.I think we can do it only after emptying the contents.
I recently encountered an idiom I haven't seen before: string assembly by StringWriter and PrintWriter. I mean, I know how to use them, but I've always used StringBuilder. Is there a concrete reason for preferring one over the other? The StringBuilder method seems much more natural to me, but is it just style? I've looked at several questions here (including this one which comes closest: ht...
Exact duplicate by same poster: http://stackoverflow.com/questions/516291/the-use-of-this-in-java Hello, what about using "this" with methods in Java? Is it optional or there are situations when one needs to use it obligatory? The only situation I have encountered is when in the class you invoke a method within a method. But it is optional. Here is a silly example just to show what I mean: ...
I'm using StringBuffer in Java to concat strings together, like so: StringBuffer str = new StringBuffer(); str.append("string value"); I would like to know if there's a method (although I didn't find anything from a quick glance at the documentation) or some other way to add "padding". Let me explain; every time I append something to the string, I want to add a space in the end, like so: ...
I need to extract information from an unstructured web page in Android. The information I want is embedded in a table that doesn't have an id. <table> <tr><td>Description</td><td></td><td>I want this field next to the description cell</td></tr> </table> Should I use Pattern Matching? Use BufferedReader to extract the informati...
  /*
   * Copyright 2003-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 mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

The principal operations on a StringBuilder 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 builder. The append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point.

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

In general, if sb refers to an instance of a StringBuilder, then sb.append(x) has the same effect as sb.insert(sb.length(), x). Every string builder has a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger.

Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.

Author(s):
Michael McCloskey
Since:
1.5
See also:
StringBuffer
String
 
 public final class StringBuilder
     extends AbstractStringBuilder
     implements java.io.SerializableCharSequence
 {

    
use serialVersionUID for interoperability
 
     static final long serialVersionUID = 4383685877147921099L;

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

    
Constructs a string builder with no characters in it and an initial capacity specified by the capacity argument.

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

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

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

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

Parameters:
seq the sequence to copy.
Throws:
NullPointerException if seq is null
    public StringBuilder(CharSequence seq) {
        this(seq.length() + 16);
        append(seq);
    }

    
    public StringBuilder append(Object obj) {
        return append(String.valueOf(obj));
    }
    public StringBuilder append(String str) {
        super.append(str);
        return this;
    }
    // Appends the specified string builder to this sequence.
    private StringBuilder append(StringBuilder sb) {
        if (sb == null)
            return append("null");
        int len = sb.length();
        int newcount =  + len;
        if (newcount > .)
            expandCapacity(newcount);
        sb.getChars(0, len);
         = newcount;
        return this;
    }

    
Appends the specified StringBuffer to this sequence.

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

Let n be the length of this character sequence 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.

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

    
    public StringBuilder append(CharSequence s) {
        if (s == null)
            s = "null";
        if (s instanceof String)
            return this.append((String)s);
        if (s instanceof StringBuffer)
            return this.append((StringBuffer)s);
        if (s instanceof StringBuilder)
            return this.append((StringBuilder)s);
        return this.append(s, 0, s.length());
    }

    
    public StringBuilder append(CharSequence sint startint end) {
        super.append(sstartend);
        return this;
    }
    public StringBuilder append(char str[]) {
        super.append(str);
        return this;
    }
    public StringBuilder append(char str[], int offsetint len) {
        super.append(stroffsetlen);
        return this;
    }

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

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

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

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

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

    

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

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

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

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

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

    
    public StringBuilder insert(int offsetObject obj) {
        return insert(offset, String.valueOf(obj));
    }

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

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

    
    public StringBuilder insert(int dstOffsetCharSequence s) {
        if (s == null)
            s = "null";
        if (s instanceof String)
            return this.insert(dstOffset, (String)s);
        return this.insert(dstOffsets, 0, s.length());
    }

    
    public StringBuilder insert(int dstOffsetCharSequence s,
                                int startint end)
    {
        super.insert(dstOffsetsstartend);
        return this;
    }

    
    public StringBuilder insert(int offsetboolean b) {
        super.insert(offsetb);
        return this;
    }

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

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

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

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

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

    
    public int indexOf(String str) {
        return indexOf(str, 0);
    }

    
    public int indexOf(String strint fromIndex) {
        return String.indexOf(, 0, ,
                              str.toCharArray(), 0, str.length(), fromIndex);
    }

    
    public int lastIndexOf(String str) {
        return lastIndexOf(str);
    }

    
    public int lastIndexOf(String strint fromIndex) {
        return String.lastIndexOf(, 0, ,
                              str.toCharArray(), 0, str.length(), fromIndex);
    }
    public StringBuilder reverse() {
        super.reverse();
        return this;
    }
    public String toString() {
        // Create a copy, don't share the array
        return new String(, 0, );
    }

    
Save the state of the StringBuilder instance to a stream (that is, serialize it).

SerialData:
the number of characters currently stored in the string builder (int), followed by the characters in the string builder (char[]). The length of the char array may be greater than the number of characters currently stored in the string builder, in which case extra characters are ignored.
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {
        s.defaultWriteObject();
        s.writeInt();
        s.writeObject();
    }

    
readObject is called to restore the state of the StringBuffer from a stream.
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOExceptionClassNotFoundException {
        s.defaultReadObject();
         = s.readInt();
         = (char[]) s.readObject();
    }
New to GrepCode? Check out our FAQ X