In this case, it is better to use mutable StringBuilder, and append characters to it on every iteration before printing it. This will let us avoid nested cicles with memory allocation for each string (we can't just use String instead of StringBuilder, because String is immutable, and we will allocate memory for it in each iteration).
I assume, that this is not a good programming practice, and the programm could rewriten like this:
public class pattern{
public static void main(String[] args){
int rows = 5;
StringBuffer sb = new StringBuffer(rows);
for(int i = 1; i <= rows; ++i){
sb.append("*");
System.out.println(sb);
}
}
}
Comments
Leave a comment