append things to String ...

Posted on 2006-05-17
Last Modified: 2011-09-20
Hello experts,

  I have a loop like:

  String myString = " ";
  for(int i=0; i<N; i++){
   myString += (String)i*10000; }

 the code becomes slower and slower when N gets larger ...
 is there any other better way (faster ways) to append things the the String ?

Question by:meow00
    LVL 92

    Accepted Solution

    Use StringBuffer or StringBuilder instead

      StringBuffer buffer = new StringBuffer(N*5);
      for(int i=0; i<N; i++){
      String myString = buffer.toString();

    LVL 23

    Assisted Solution

    Further to objects comment above:

    StringBuilder is faster than StringBuffer.  Use StringBuilder if you can (it is not "thread safe").  If you need it to be thread safe then you'll have to use StringBuffer.  
    LVL 30

    Expert Comment

    Keep in mind that StringBuilder is available only in Java 5, so if you have a prior version of Java, you need to stick to StringBuffer.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    Suggested Solutions

    This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
    Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
    Video by: Michael
    Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
    This video teaches viewers about errors in exception handling.

    759 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    8 Experts available now in Live!

    Get 1:1 Help Now