[JAVA] String Buffer practice

Processing that repeats "u" and "mi" alternately

Method 1 is because sentences are added with new String Buffer every time in the iterative process. Processing time is longer than that of method 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)?"U":"Mi");	
		}
		return answer;
	}
	
	public static String method2(int n) {
		StringBuffer sb = new StringBuffer();
		for(int i = 0 ; i < n; i++) {
			sb.append(((i%2==0)?"U":"Mi"));	
		}
		answer = sb.toString();
		return answer;
	}
}


Recommended Posts

String Buffer practice
String
Array practice
String puzzle
[Practice] ArrayList
Array practice 2
ArrayList practice
[Practice] Enumeration
String replacement
Liar String