String & StringBuffer again......

hi all,
after coding for 1 year with java (before c++ for years) i used the stringbuffer class for the first time a few days ago.
i implemented a search which has to do lot's (!) of string operations.
the search was very slow, so i tried stringbuffer.
i replaced and changed all the string stuff into stringbuffer stuff - but the performance was still bad...
so could the following be the problem:
stringbuffer don't know important functions like 'indexof(String)'.
so everytime i need indexof (for example), i do the toString() function...
now my first question:
is all the stringbuffer advantage gone if i use toString() at one or to places ==> how much performance will this cost (in a loop...)?
my second question:
what's faster, deleting the content of an used stringbuffer with delete(int,int) or just creating a new with new stringbuffer(String) ?
thanx a lot,
andi

What you should probably do is use "javap -c" to look at the bytecode produced in your class. Then you can see exactly how many objects are being created for each way of coding the String and StringBuffer operations.
To answer your question about toString(), it creates an extra String object when called, but does not copy the characters. However, if you subsequently change the original StringBuffer, the characters in it will need to be copied. Therefore, calling toString() and then changing the StringBuffer further can have a serious impact on performance.

Similar Messages

  • Truncating Strings(stringbuffer)

    Hello again
    im trying to delete portions of a string that are over a certain length, i know i need to use StringBuffer and public delete(int start, int end) command, but i am having trouble working it in, how do i initialize a Stringbuffer?
    Stringbuffer serverNameBuff=new StringBuffer(serverName); is meant to create a StringBuffercopy of the string serverName, what am i doing wrong?
    THankyou
    dom

    lol damn, sorry, i see now...lowercase b...nevermind, but thanks anyway

  • How to display the multiple lines text in a single - String, StringBuffer

    Hi,
    I have a textarea field named Decription which contains more than one line seperated by new line.I need to display those five lines in a single text without breaking. Is it possible? I am getting ArrayIndexOutOfBoundsException while i reached to the end of the line. Plz help me how to align the below code so that i can display the lines as a single line in my excel sheet.
                        if(op.getDescription()!=null)
                            String[] oppDescs = op.getDescription().split("\n");
                            StringBuffer sb = new StringBuffer();
                            for(int i1=0; i<=oppDescs.length-1;++i1)
                                *writeFile(sb.append(oppDescs[i1]), valueWriter);*
                         } else {
                            writeFile(op.getDescription(), valueWriter);
    private void writeFile(java.lang.Object value,PrintWriter valueWriter)
            if(value!=null)
                valueWriter.print(value);   
        }Thanks and Regards

    previous was java1.5
    heres a 1.1 - 1.4 version
    String[] oppDescs = op.getDescription().split("\n");
    StringBuffer sb = new StringBuffer();
    for(int i = 0; i < oppDescs.length : i++){
      sb.append(oppDescs);
    sb.append( '\t' );
    writeFile(sb.toString(), valueWriter );Edited by: simon_orange on 31-Oct-2008 13:02                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • OutputStream to String/StringBuffer?

    How can I convert a OutputStream into a String or StringBuffer?

    <OutputStream>.toString();In what context do you use this?It is inherited from Object.
    This will give you a "string representation" of the stream object. Normally, this will just return an object identifier. I use this when I'm debugging or printing low level logging messages to help determine exactly which object I'm dealing with.
    - K
    PS - If you want to convert a stream to a String, you probably want to be using a Writer instead of a stream. Writers are character set encoding aware...

  • JNI: Getting String | StringBuffer  to Java from C using input argument

    I've written a native method in C which takes command String from Java, executes the command, and obtains both an integer return_code and a C-string result_string as an output. The return_code goes back to Java from the return statement at the end of the native method...my problem is, that I would like to pass into the native method either a String or StringBuffer, and use that to relay the result_string back to the Java code, as well. Eg., loosely, if I have a
    JNIEXPORT jint JNICALL ExecuteCmd
    (JNIEnv *env, jclass jcls, jstring cmdString, jobject returnBuffer)
    where jobject returnBuffer is a StringBuffer created as StringBuffer(2048), I'd like to take return_string once I have it and do something like
    returnBuffer = env->NewStringUTF(result_string);
    (I know the syntax env->NewStringUTF is a bit different to what's in the JNI book, but it's what works on the HP-UX system I'm using.)
    I know already that this particular bit of code doesn't work. My question is, does the general idea have any potential to work, or am I trying to do something that's impossible?

    Your general approach works just fine. What you have to do is use JNI to find the appropriate method for the StringBuffer class, and invoke it.

  • String & StringBuffer

    Hi,
    Why String objects are Immutable?
    and StringBuffer objects are mutable.
    what is the logic behind this design.
    thanks in advance.

    My theory on this is that Strings occupy fixed contiguous areas of memory. To alter them may corrupt the area of memory that comes immeadiately after a particular String. Therefore it is safe to not let programmers to alter them. A StringBuffer on the other hand overcomes this restriction and will allow expansion of itself by the programmer to other areas of memory, under control of the compiler, when required.

  • String , StringBuffer Performace

    I am trying to concatenate strings. In the following program, f2 and f3 take less than a second while f1 takes about 17 seconds on my P4 1.3 Ghz pc. Any ideas why += operation takes more time.
    public class StringTest
    public static void main(String s[])
    long start_time = System.currentTimeMillis() ;
    if (s[0].equals("1")) f1();
    if (s[0].equals("2")) f2();
    if (s[0].equals("3")) f3();
    long end_time = System.currentTimeMillis() ;
    System.out.println("Time in sec: " + (end_time-start_time)/1000);
    public static String f1()
    String s = "";
    for (int i=0;i<10000;i++)
    s += new String("Helloworld");
    return s;
    public static String f2()
    StringBuffer s = new StringBuffer();
    for (int i=0;i<10000;i++)
    s.append("HelloWorld");
    return s.toString();
    public static String f3()
    String s = "";
    for (int i=0;i<10000;i++)
    s = new String("Helloworld");
    return s;
    }

    It's terrifying indeed...
    Here are my results on a IBM ThinkPad PM 1.7 GHz 512 Mb with Windows XP Pro SP2
    For JVMs from 1.4 to 1.6.
    (I modified the println line to get double result)
    java -version
    java version "1.4.2"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2)
    Classic VM (build 1.4.2, J2RE 1.4.2 IBM Windows 32 build cn142-20040926 (JIT ena
    bled: jitc))
    java StringTest 1
    Time in sec: 1.682
    java -version
    java version "1.5.0_05"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_05-b05)
    Java HotSpot(TM) Client VM (build 1.5.0_05-b05, mixed mode)
    java StringTest 1
    Time in sec: 26.588
    java -version
    java version "1.6.0-beta"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.6.0-beta-b59)
    Java HotSpot(TM) Client VM (build 1.6.0-beta-b59, mixed mode, sharing)
    java StringTest 1
    Time in sec: 32.76
    Aaaaaaaaaaaaaaargh!!!

  • String problem again!!

    I have a string and I wanted to keep it's value evenwhen it passes from one method to another!!
    Is this possible in any way!?
    Ie acts like an object rather then like a primitive?

    Not exactly ...
    In the example below the value of a dosent change.
    public class Test{
         public Test(){
              String a = "Hello, World [1]";
              String b = updateHelloWorld(a);
              // Value of 'a' did not change.
              System.out.println(a);
              System.out.println(b);
         public String updateHelloWorld(String a){
              a = "Hello, World [2]";
              return a;
         public static void main(String[] args){
              new Test();
         class StringContainer{
              String aString;
    }While in the following example the value a changes because the string is raped in another object!
    public class Test{
         public Test(){
              StringContainer a = new StringContainer("Hello, World [2]");
              StringContainer b = updateHelloWorld(a);
              // Value of 'a' does change!!!.
              System.out.println(a.aString);
              System.out.println(b.aString);
         public StringContainer updateHelloWorld(StringContainer a){
              a.aString = "Hello, World [2]";
              return a;
         public static void main(String[] args){
              new Test();
         class StringContainer{
              public String aString;
              public StringContainer(String aString){
                   this.aString = aString;
    }

  • String to StringBuffer

    How do i convert String object to StringBuffer object?

    You can initialize a new Stringbuffer to a String
    this way:
    String yourString = "A string";
    StringBuffer sb = new Stringbuffer(yourString);
    Alpha75

  • Building SQL String ?

    I am trying to build a SQL String and send it to the database...
    this is how i am trying to form a query string
    StringBuffer sBuff = new StringBuffer(250);
    sBuff.append("old information")
    sBuff.append("new history added twice");
    String caseObjId = "2567034";
    StringBuffer queryBuff = new StringBuffer(250);
    queryBuff.append("UPDATE table_case ");
    queryBuff.append("SET case_history =" + sBuff);
    queryBuff.append("WHERE objid =" + caseObjId);
    i am getting SQL Exception saying
    com.sybase.jdbc2.jdbc.SybSQLException: Incorrect syntax near 'information'.
    let me know what where i am doing mistake
    thanks
    KM

    The previous posters are right on target for debugging your problem; if you printed out the query that's giving you problems, you would see:
    UPDATE table_case
    SET case_history =old informationnew history added twice
    WHERE objid =2567034 and the problem then becomes obvious that the string/varchar data needs to be quoted.
    That will fix your immediate problem.
    However, since you are obviously a newbie, I'll tell you how to fix 2 or 3 more problems; don't use Statement, use PreparedStatement and bind your parameter values.
    <rant>
    First, when a database executes a SQL statement for the first time, it has to "parse" it. "parsing" is an awful like compiling in that it often takes 100 times longer or more to compile a bit of code than it does to execute it. A good database will check a cache of parsed SQL to see if it doesn't need to parse again, but it often relies on an exact match of the SQL. If you use Statement and change the value of case_history or objid, it's not an exact match. However, if you use PreparedStatements, your values aren't part of the SQL; therefore you get a lot more matches in the parse cache and the database saves a huge amount of work.
    Second, when you build up SQL with embedded values like you're doing, you have to deal with any special characters appropriately; in particular the single quote character; for example, if you have a LAST_NAME column, you need to support the name "O'Conner"; the single-quote in the middle has to be recognized and properly escaped. This problem simply goes away with parameter bindings; the code and the data are widely seperated and there's no question where the boundary is.
    Third, building up SQL in the way you did is the technique that causes a major security hole an poorly coded applications. Let's say you're building an e-commerce site that will keep customer credit card numbers on file (risky) and want a function to display credit card numbers given an account number (not really a good idea, but it illustrates the technique). You have code like:
    StringBuffer queryBuff = new StringBuffer();
    queryBuff.append("SELECT CC_FIRST_NAME, CC_LAST_NAME, CC_NUMBER, CC_EXP ");
    queryBuff.append("FROM CARD_DATA);
    queryBuff.append("WHERE account_number  =" + acct_number);this will work just great when a user enters their account number of "1234567", and it will work just great (for the hacker) when the account number is entered as "1234567 or (CC_FIRST_NAME = 'Bill' and CC_LAST_NAME = 'Gates')"; the hacker's add-ons are treated as code, not data, and the e-commerce site spits up a customer's data to an authorized person. Again, parameter binding prevents this and add-ons get treated as part of the account number, probably generating a data-type error on the database. Obviously, you can validate the data to numerics in this example, but if you use PreparedStatement instead, you don't have to think, it takes care of itself.
    </rant>

  • Fastest way to access data between String and char[]

    Hi all,
    I've been programming a small String generator and was curious about the best and fastest way to do so.
    I've done it in two ways and now hope you can tell me if there is a "more java version" or fastest way between those two or if I'm totally wrong as some classe in the API already does that.
    Here are the codes:
    version 1:
            //describe the alphabet
         String alphabet = "abcdefghijklmnopqrstuvwxyz";
         //The "modifiable String"
         StringBuffer stringBuffer = new StringBuffer();
         //Just put the temporary int declaration outside the loop for performance reasons
         int generatedNumber;
         //Just do a "for" loop to get one letter and add it the String
         //Let's say we need a 8 letters word to be generated
         for (int i=0; i < 8; i++)
             generatedNumber = (int)(Math.random() * 26);
             stringBuffer.append(alphabet.charAt(generatedNumber));
         System.out.println(stringBuffer.toString());
         stringBuffer =null;version 2:
            //describe the alphabet
         char[] alphabetArray = {'a', 'b', 'c', 'd', 'e', 'f',
                        'g', 'h', 'i', 'j', 'k', 'l',
                        'm', 'n', 'o', 'p', 'q', 'r',
                        's', 't', 'u', 'v', 'w', 'x',
                        'y', 'z'}
         //The "modifiable String"
         StringBuffer stringBuffer = new StringBuffer();
         //Just put the temporary int declaration outside the loop for performance reasons
         int generatedNumber;
         //Just do a "for" loop to get one letter and add it the String
         //Let's say we need a 8 letters word to be generated
         for (int i=0; i < 8; i++)
             generatedNumber = (int)(Math.random() * 26);
             stringBuffer.append(alphabetArray[generatedNumber]);
         System.out.println(stringBuffer.toString());
         stringBuffer =null;Basically, the question is, what is the safest, fastest and more "to the rules" way to access a char in a sequence?
    Thanks in advance.
    Edited by: airchtit on Jan 22, 2008 6:02 AM

    paul.miner wrote:
    Better, use a char[] instead of a StringBuffer/StringBuilder, since you seem to know the size of the array in advance.
    Although I imagine making "alphabet" a char[] has slightly less overhead than making it a String
    1. It's a lot clearer to write it as a String.
    2. You can just call toCharArray() on the String to get a char[], instead of writing out each char individually.
    3. Or if you're going to be using a plain alphabet, just use (randomNumber + 'a')
    And use Random.nextInt()Hello and thx for the answers,
    I know I shouldn't put constants in my code, it was just a piece of code done in 1 minute to help a colleague.
    Even if it was just a one minute piece of code, I was wondering about the performance problem on large scale calculating, I mean something like a 25 characters word for billions of customers but anyway, once again, the impact should be minimal.
    By the way, I didn't know the Random Class (shame on me, I still don't know the whole API) and, I don't understand why I should be using this one more than the Random.Math which is static and thus take a few less memory and is easier to call.
    Is it because of the repartition factor?
    According to the API, the Random.Math gives (almost) a uniform distribution whether the Random.nextInt() gives a "more random" int.
    I

  • How can labview update the string control (text-edit box) after we have pressed the carriage return key on the keyboard during text-editing within that box?

    Dear readers,
    I have been trying to work out how to get labview to detect the event when a 'string' control has been modified, where the user has finished editing the string either by 1) pressing the enter key on the keyboard, or by 2) taking the focus away from the string control again. For example.. if I use the mouse to click on the string control and then I type 1234 into the box, I would like to have a routine that does something once the user hits the Enter key of the keyboard, or when the user takes the focus away from the string control again by clicking on something else. I would like the routine to respond even when the user didn't change anything in the text box (such as when we mouse-click on the edit box to go into edit mode, and then mouse-click on something else to remove the focus with no changes to the contents in edit-box).
    The purpose of my routine is to have a edit-box for a user to change for example the centre-frequency of a vector network analyser, so that the centre-frequency of the network analyser can change once the user finishes entering a new value in the text-edit box by hitting Enter key after the number is keyed in. Even if the user has clicked on the edit box, but changes their mind by mouse-clicking on something else to remove focus from the edit box, I would still like labview to detect the event when the control loses focus, so that the centre frequency can be updated anyway (to the same value that was already in the edit box).
    So far, I've tried set the string control option to 'limit to single line', so that I can try to scan for a carriage return .. '\n' ... pattern in the string. Unfortunately this doesn't work because labview doesn't seem to attach the '\n' to the end of that single line.
    Could someone please suggest ways to set a flag when a user hits Enter during text-edit mode of a string control, or when focus has been removed from the string control?
    While I've only described my problem for controlling a single control parameter on the gpib device, I'd like to make this feature work so that I can do the same kind of thing with other control parameters as well.
    Thanks so much in advance.
    Kenny

    Hi Kenny,
    instead of using the event structure, you can directly achieve to what you want by the KeyFocus property of the string control.
    - Enable Limit to single line option
    - Create the property KeyFocus in read mode and connect an indicator
    Each time you click on the string to modify it KeyFocus is True; when you click away or hit Enter KeyFocus is False.
    You can toggle your settings when KeyFocus changes from True to False.
    Alberto

  • Substitution String in Row Template order dependant

    Hi Folks,
    This questions is related to an earlier Complex Detail Report Layout: Can it be done? about building a complex row template (thanks for your help, Vikas!).<br><br>
    Having built the row template (Named Columns) and tested it in a separate application, I have been preparing to incorporate it into the target application. (Here's a screen shot of the work in progress.) I decided to see if I could use column aliases with the substitution strings and so added an alias to the query for the report.<br><br>
    Strange values appeared (like a "Y" for a Project Name) and initially I thought the aliases wouldn't work, so I backed the change out. However, it was now quite apparent that the substitution strings were not taking their values from the column names, as I expected. I was able to put the values in the correct place by modifying the order of the columns selected in the query.<br><br>
    Am I misunderstanding? Shouldn't the order of the columns in the select statement be irrelevant when named columns are used? <br><br>
    Since the order in the query is NOT the order displayed in the template, and I have nearly 30 fields, (many of which are dates, and I couldn't possible guess which is which if the substitution doesn't work properly), it seems important to understand how to ensure the proper values appear in the report.<br><br>
    Many thanks for your help,<br><br>
    Petie

    I take it back. This is whacked. Please take a look at the picture (http://tinypic.com/view/?pic=nygyu0)
    OK, I had a select statement:
    select ps.project_name, ps.project_manager,  ps.gts_dependant, ps.gxp_relevant from project_status ps, eprs_program p
    where
    ps.program_id = p.id and
    p.program_number = :P6_PROGRAM_NUMBERThis populated the fields #PROJECT_NAME#, #PROJECT_MANAGER#, etc. properly.
    I even switched the order around and put the ps.project_manager ahead of the ps.project_name and template still worked.
    I restored the order and checked again. All is good.
    I changed the query and added an alias like so:
    select ps.project_name as "PROJ_NAME", ps.project_manager,  ps.gts_dependant, ps.gxp_relevant from ...The report showed the substitution string "#PROJECT_NAME#" (as expected, because the column was now aliased.) So this is good.
    I went to the row template definition and changed the substitution string #PROJECT_NAME# to #PROJ_NAME# to match the query -- and the substitution strings broke again!
    The report template now behaves as described earlier; being position dependant. Now I suspect that this is a bug, and not something caused by my mucking around.
    I would greatly appreciate your thoughts on the matter and potential workaround. At this point, I will likely delete the region and try creating a new region. I would hate to loose the whole page, the top part was a lot of effort. <sigh>
    Thanks,
    Petie

  • Is there any String format class available in J2ME?

    Hello,
    I am looking for a Formating class which should format a string. For example ( This is Java SE code):
    int num = 999;
                String str = " is my lucky number.";
                String s = String.Format("The Number : %d %s", num, str);I could not find any formatter class nor any direct api from String/StringBuffer class to format a string.
    Any suggestion on this is highly appreciated.
    Thank You.
    Regards,
    DK

    sojourner_jdk wrote:
    Hi DarrylBurke,
    You are right. Its not "Format". String has "format" function ..
    String s = String.format("The Number : %d %s", num, str);Is there such class/api in J2ME?
    Thanks,
    Regards,
    -DKIn J2ME MIDP, [String has no "format" function|http://java.sun.com/javame/reference/apis/jsr118/java/lang/String.html|javadoc].

  • How to remove only the last element of spreadsheet string

    I use path to string option to store image path into database and while retrieving the string is again converted into path but it gives out an error as the output of array to spreadsheet string gives out a tab at the end which is unable for the IMAQ read file to recognise.but when i use the path of the image directly into IMAQ readfile the image is opened . so how to remove the tab only at the end of output of the spreadsheet string(whose length can vary)? I have also attached my program with this.
    Attachments:
    retrieve_images_from_DB.vi ‏65 KB
    file_path_to_db_(images).vi ‏40 KB
    create_table_for_images.vi ‏45 KB

    indhu wrote:
    > Thanks for your reply!
    > But my problem is to remove only the last element(which is a tab or an
    > alphabet) from a spreadsheet string of any length.
    If you just want to remove the last character of a string just use the
    String Size function reduce the result by one and wire it together with
    the string to the Split String function.
    Rolf Kalbermatter
    Rolf Kalbermatter
    CIT Engineering Netherlands
    a division of Test & Measurement Solutions

Maybe you are looking for