Answer to Question #136503 in Java | JSP | JSF for A.K

Question #136503
Evaluate the JAVA code snippet below, then motivate why this is representative of good programming practices or not.
public class pattern{ public static void main(string[] args){ int rows = 5; for(int i = 1; i <= rows; ++i){ for(int j=1;j<=I;++j){ system.out.print(“*”); } System.out.println(); } }
1
Expert's answer
2020-10-04T23:45:58-0400

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);
     }
   }
 }

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS