Help us understand the problem. What is going on with this article?

StringBufferの練習

More than 1 year has passed since last update.

”う”と”み”を交互に繰り返す処理

メソッド1は繰り返し処理のところで毎回new StringBufferで文章が追加されるため
メソッド2に比べて処理時間がかかる。

StringBuffer.java
package javaStudy;

public class StringBufferExam {
    public static String answer = "";

    public static void main(String[] args) {
        System.out.println(method1(50));
        System.out.println(method2(50));        
    }

    public static String method1(int n) {
        for(int i = 0 ; i < n; i++) {
            answer += ((i%2==0)?"う":"み");   
        }
        return answer;
    }

    public static String method2(int n) {
        StringBuffer sb = new StringBuffer();
        for(int i = 0 ; i < n; i++) {
            sb.append(((i%2==0)?"う":"み"));  
        }
        answer = sb.toString();
        return answer;
    }
}
sumy
Java勉強中です。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away