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.

Similar Messages

  • 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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • 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

  • 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.

  • 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 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 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

  • 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].

  • JDBC:KPRB string size limits-NEED HELP!

    Hello All.
    Please, I need your help.
    I have the problems in Oracle 9.2.0.6 with stored java and jdbc:kprb internal driver.
    I try to put string(more than 32K) into LONG-type field using following java class:
    import oracle.sql.CLOB;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.io.Reader;
    import java.io.CharArrayReader;
    public class LongTest {
    public static void insertLong()
    throws Exception {
    Connection con = DriverManager.getConnection("jdbc:default:connection:");
    //generate large string
    StringBuffer stringBuffer = new StringBuffer();
    for (int i = 0; i < 100000; i++) {
    stringBuffer.append("qwerty");
    String st = stringBuffer.toString();
    //put large string to long-type field
    PreparedStatement pst = null;
    try {
    pst = con.prepareStatement("insert into TEST_LONG (ldata) values (?)");
    pst.setString(1, st);
    pst.execute();
    } finally {
    if (pst != null) {pst.close();}
    But I get error from jdbc:kprb about limitation of data size for this type(LONG).
    But it works well in oracle 10.2.0.1...
    Has anybody a solution of how to do this in oracle 9.2.0.6???
    thanx!

    Hi,
    THis is a known limitation in the 92 RDBMS solved in 10g.
    Kuassi http://db360.blogspot.com

  • Problem in retriving string

    Hi all,
    i'm finding problem in retriving string
    i'm getting only first line as output
    the coding is
    import java.io.*;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    class newprg2
    public static void main(String args[]) throws IOException
    InputStream in = new FileInputStream("e:/rag.txt");
    //OutputStream out = newFileOutputStream("e:/rag1.txt");
    int c,pos,pos1;
    String s=new String();
    StringBuffer sb = new StringBuffer();
    while((c=in.read())!=-1)
    sb.insert(0,(char)c);
    sb = sb.reverse();
    s = sb.toString();
    pos = s.indexOf("verify scan_test",0);
    s=s.substring(pos+1);
    while(pos>=0)
    pos=s.indexOf("_cpdp_=",pos);
    pos=s.indexOf("=",pos);
    pos1=s.indexOf(';', pos);
    s=s.substring(pos+1,pos1);
    System.out.println(s);
    }here's the input file
    verify scan_test  {
      Abb {* verify:0  Value:0  lifecycle:0 *}
      W tset_tp;
      S {  _cpdp_=YYYY10YYYYYYYYYYYYYYYYYYY;
      Abb {* Begin loop test *}
      S {  _cpdp_=YYYY10YYYYYYYYYYYYYYYYYYY;
      S {  _cpdp_=YYYY110YY1YYYYYYYYYYYYYYY;
      S {  _cpdp_=YYYY110YY1YYYYYYYYYYYYYYY;
      S {  _cpdp_=YYYY111YY1YYYYYYYYYYYYYYY;
      }now i'm getting output as
    YYYY10YYYYYYYYYYYYYYYYYYY
    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
            at java.lang.String.substring(Unknown Source)
            at newprg2.main(newprg2.java:42)but i want output as
    YYYY10YYYYYYYYYYYYYYYYYYY
    YYYY10YYYYYYYYYYYYYYYYYYY
    YYYY110YY1YYYYYYYYYYYYYYY
    YYYY110YY1YYYYYYYYYYYYYYY
    YYYY111YY1YYYYYYYYYYYYYYY

    Manivel wrote:
    raghavan,
    Alter the code inside the while loop like below, you will get as what you expected.
    while (pos >= 0) {
    s = s.substring(pos + 1);
    pos = s.indexOf("_cpdp_=", pos);
    pos = s.indexOf("=", pos);
    pos1 = s.indexOf(';', pos);
    String ss = s.substring(pos + 1, pos1);
    System.out.println(ss);
    }-ManiI'm sorry, but, if you are simply going to spew out the answer to someones homework, you could at least explain what was wrong (before the code). They don't care in the least, but having read it, they may retain at least some spark of the meaning that the lesson was intended to teach. Like this it's just cut and paste, and who gives a damn. They learn a lot that way, NOT!

  • How to remove "\r" from a string

    I have a string, it has "\r" and "\n" eg : "abcde dfs \r \n acdsa \r\ncdaacdla"
    when I display this on a panel or print from panel, a box appears at the end, I think its because of \r characters.
    Is there any easy way to remove them.?
    please help thanks.

    sorry i dont which other replace you are talking
    about....btw i am using 1.3.xDon't worry, you'll evolve someday ;~)
    Just dump it into a StringBuffer, and page through and delete manually.
    String removeRs(String string)
       StringBuffer b = new StringBuffer(string.length());
       for(int x = 0 ; x < string.length() ; x++)
          if(string.charAt(x) != '\r')
             b.append(string.charAt(x));
       return b.toString();
    }

  • Converting unicode string to ASCII

    I'm using a 3rd party API and I'm receiving the following unicoded string through an API:
    Original string: "Bill%u002b%u002526%u002bHarry%u002bUsers"
    The ASCII value is supposed to be:
    Desired string: "Bill & Harry Users"
    How do I convert the original string to the desired string?
    Any sample code would be greatly appreciated!
    Thanks

    could look someething like:
    public class Decoder
      public static String decode(String string)
        StringBuffer result = null;   
        int pos = 0;
        int idx;      
        if( string != null )
          result = new StringBuffer();
          while( pos < string.length() )
            idx = string.indexOf("%u", pos);
            if( idx >= 0
                && idx + "u0000".length() < string.length() )
              result.append( string.substring(pos, idx));
              pos = idx;
              result.append( (char)Integer.parseInt(
                      string.substring( idx + "%u".length(), idx + "%u0000".length() )));          
              pos += "%u0000".length();
            else
              result.append( string.substring(pos));
              pos = idx;
        return result != null ? result.toString() : null;
    }

  • 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>

  • Replace a String pattern

    I have the following string:
    String="TVBeginEsternTVEnd
    MovieBeginN/AMovieEnd
    TVBeginPacificTVEnd
    MovieBeginN/AMovieEnd......................"
    I need to replace only the contents between TVBegin and TVEnd. The result (If I want the content=Midwest) should look as follow:
    String="TVBeginMidwestTVEnd
    MovieBeginN/AMovieEnd
    TVBeginMidwestTVEnd
    MovieBeginN/AMovieEnd......................"
    Do you have any suggestions on how to replace the string content?
    Thank you very much!

    Sheshy,
    We can tell you how to do small things, one at a time, all day long. You really need to learn how to read the documentation. Go read the documentation for String, StringBuffer. You can figure it out. Really.

Maybe you are looking for

  • Opening signed documents crashes Acrobat 9.4.4.

    This issue happens with Actobat 9.4.3 and 9.4.4: With one or more PDF files already open (could be a published document simply open for review), open a document that includes a digital signature. The file with the digital signiture opens, but then so

  • XI Lookup Error

    I am New to XI Lookups. i am getting following error in IR Mapping when i try to activate my message mapping! SERVER: XI 3.0   PATCH: SP15 ERROR---- Activation of the change list canceled Check result for Message Mapping ZSAPTVDP_to_INSMASTER_NEW | h

  • I have no sound after updating to iOS 6.1.3

    After updating I lost sound. Tried restoring and still no sound. Guess I'll have to get a new phone...any other suggestions?

  • Menubar hidden in webgui

    Hi All, I am creating a transaction (transaction code : ME51N) iview  of type webgui(SAP GUI for HTML),  i am not getting the header part(menu bar, save buttons etc ) in my view, Please help me solving this issue Regards Pradeep P N

  • Is Mail setting Mime format correctly?

    I am writing software that processes mail using the php pear class mimemail. This software is unable to processes a mail sent using Mac mail that contains a word attachement where the word attachement has an image in the header. Obscure I know! I don