Why does System.out.println() perform a subsequent transition to a new line after the output of five values, and not after the output of each value?

 public class TwoDArrays { public static void main(String args[]) { int twoD[][] = new int[4][5]; int i, j, k = 0; for (i = 0; i < 4; i++) for (j = 0; j < 5; j++) { twoD[i][j] = k; k++; } for (i = 0; i < 4; i++) { for (j = 0; j < 5; j++) System.out.print(twoD[i][j] + " "); System.out.println(); } } } 
  • There are no errors in this code. Sample Code from the Java 8 Book Complete Guide 9th Edition. - Pao_Cy
  • 3 3 3 3 3 new line 2 3 4 1 3 new line 3 3 4 2 3 new line 2 3 4 5 3, if you don’t understand why this is the case, then read the schild textbook again! (I wrote the numbers for the boom) - Sanaev

1 answer 1

If you did not put braces after the loop operator, then only the method following it will be executed in the loop, i.e.

 for(j = 0; j < 5; j++) System.out.print(twoD[i][j] + " "); 

To make both console output methods run in an internal loop, write this:

 for(j = 0; j < 5; j++) { System.out.print(twoD[i][j] + " "); System.out.println(); }